http://qs321.pair.com?node_id=2464

vroom has asked for the wisdom of the Perl Monks concerning the following question:

Use reverse in scalar context. It just reverses by bytes or characters. In a list context it will reverse the elements of a list:
$revstr = reverse($str); # reversed by character $revwords = join(" ", reverse split(/ /, $str));

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I reverse a string or the words in a string?
by ariels (Curate) on Dec 03, 2000 at 17:21 UTC
    This also works for reversing the order of words, but is trickier.
    $str = 'hacker. Perl another Just';
    ($revwords = $str) =~ s/(\S+)/reverse $1/ge;
    $revwords = reverse $revwords
    
Re: How do I reverse a string or the words in a string?
by pokemonk (Scribe) on Jul 21, 2001 at 04:16 UTC
    #lie about myself $str='i am a sexy bastard'; #split the words @words=split ' ', $str; #revers 'em @words=reverse @words; #join 'em $reversestr=join ' ', @words;

    Edit by tye to include wine's suggestion

      You probably want to joint them with a space:

      $reversestr=join ' ', @words;

Re: How do I reverse a string or the words in a string?
by Anonymous Monk on Apr 16, 2004 at 03:51 UTC
    I dont know coding in Perl. I will just tell you an algorithm that strikes me. I expect that Perl has some delimiter for a string like C++ has '\0'. I will refer to the delimiter character to as delimiter The algorithm is simple,
    Start from the end character and traverse till first. Begin loop if character index= first then print string(current index) else if character = ' ' then /*space*/ print string(current index) print space set character = delimiter /* Here I am cutting the string. You can cal +l some garbage collecting function to free up the rest of the memory +space*/ end if End loop /* This algorithm will just print the string in reverse worded way. Bu +t in case you need a reversed string you can go on appending whatever + is printed here to the result string*/

    Originally posted as a Categorized Answer.

Re: How do I reverse a string or the words in a string?
by Anonymous Monk on Dec 24, 2002 at 01:24 UTC
    what does it say when you reverse fremme neppa venette?

    Originally posted as a Categorized Answer.

Re: How do I reverse a string or the words in a string?
by Anonymous Monk on Jan 31, 2003 at 13:51 UTC
    fremme neppa venette

    Originally posted as a Categorized Answer.

A reply falls below the community's threshold of quality. You may see it by logging in.