http://www.perlmonks.org?node_id=589710


in reply to Five Ways to Reverse a String of Words (C#, Perl 5, Perl 6, Ruby, Haskell)

My dutiful contribution in languages not listed in OP; first Rexx ...

say word_reverse( " one two three four " ) exit word_reverse: procedure parse arg string new = '' do w = 1 to words( string ) new = word( string , w ) new end return strip( new , 'T' )

... and similar in (a)sh (as found on FreeBSD 6.x) ...

word_reverse() { local string="$1" new='' for s in $string do new="$s $new" done printf "%s" "${new%% }" } word_reverse " one two three four "

Replies are listed 'Best First'.
Re^2: Five Ways to Reverse a String of Words (C#, Perl 5, Perl 6, Ruby, Haskell)
by sgt (Deacon) on Dec 15, 2006 at 00:24 UTC

    not too sure about ash but you get less chars with:

     print "${new% }"

    another way showing off some aspects of modern shells but still a bit longish...

    % stephan@labaule (/home/stephan) % % cat rev.sh #!/bin/ksh93 function rev { nameref s=$1; typeset a=( $s ); integer n=${#a[*]} i; s=; n=n-1 for i in {$n..0}; do s+="${a[i]} "; done; s=${s%?} } s=" one two three four " rev s print "[$s]" % stephan@labaule (/home/stephan) % % ksh93 rev.sh [four three two one]
    enjoy ;) --steph