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

Hey,
print join ' ', q/teY rehtona lreP .rekcah/;

and
print reverse join ' ', q/teY rehtona lreP .rekcah/;

Both of the code prints the same answer
What does the reverse function do here??

--prasanna.k

Replies are listed 'Best First'.
Re: I find some strange on this code ? Sort the issue
by borisz (Canon) on Feb 01, 2005 at 09:05 UTC
    You call reverse in list context, but your list contains only one element!
    You might want to call it in scalar context to get a reversed string.
    print scalar(reverse join ' ', q/teY rehtona lreP .rekcah/);
    Read all about perldoc -f reverse here.
    Boris
      You should test your answers. It returns "hacker. Perl another Yet" instead of "Yet another Perl hacker."
        Funny, I did not notice that.
        print join ' ', reverse split ' ', reverse q/teY rehtona lreP .rekcah/
        here is a even cooler example of reverse.
        Boris
Re: I find some strange on this code ? Sort the issue
by holli (Abbot) on Feb 01, 2005 at 09:43 UTC
    Indeed, that is kind of a pitfall.
    example from here:
    $name = reverse("gnat"); # SCALAR context, -> tang @r = reverse("gnat","tom"); # LIST context -> ("tom", "gnat")

    holli, regexed monk
Re: I find some strange on this code ? Sort the issue
by radiantmatrix (Parson) on Feb 01, 2005 at 14:43 UTC

    join takes a list as its second argument, but you are passing a string.

    What it appears you want to do is:

    print scalar reverse,' ' for qw[teY rehtona lreP .rekcah];

    The qw// creates the list, and then for each element, prints the reverse of the string (thus the 'scalar'). Or, you could try:

    print scalar reverse,' ' for split ' ', q[teY rehtona lreP .rekcah];

    If you really wanted it to be a string.

    radiantmatrix
    require General::Disclaimer;
    s//2fde04abe76c036c9074586c1/; while(m/(.)/g){print substr(' ,JPacehklnorstu',hex($1),1)}

Re: I find some strange on this code ? Sort the issue
by Anonymous Monk on Feb 01, 2005 at 14:41 UTC

    Either you find something strange in the code or you don't.

    Language issues aside... I suspect you might want something like this:

    join ' ', map { scalar reverse($_) } qw/teY rehtona lreP .rekcah/;

    Sorta complicated, though. Surely there's a better way?

Re: I find some strange on this code ? Sort the issue
by johnnywang (Priest) on Feb 01, 2005 at 18:26 UTC
    I assume the following would work:
    print join ' ', map{scalar(reverse split //) } qw/teY rehtona lreP .re +kcah/; __DATA__ #output Yet another Perl hacker.
    or
    print join ' ',reverse split / /,scalar(reverse split //, q/teY rehton +a lreP .rekcah/;