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

print scalar (reverse(1,"ab")); # prints "ba1" ;......Can anyone give me the explanation for the output ? I was expecting the output as "ab1" and not "ba1"

Replies are listed 'Best First'.
Re: reverse function
by moritz (Cardinal) on Jun 29, 2012 at 11:57 UTC

    As the documentation for reverse explains, using it in scalar context does string reversal, not list reversal.

    Thus it joins all arguments into a string and reverses it.

    If you want the other output, either leave off the scalar, or write

    print join '', reverse(1, 'ab'));

    Note that this behavior confuses many newcomers (though usually they wonder why print reverse "abc"; doesn't reverse anything) and is inconsistent with how things are generally done elsewhere in Perl 5, so in Perl 6 reverse always reverses lists, and flip always reverses strings.

Re: reverse function
by daxim (Curate) on Jun 29, 2012 at 12:00 UTC
    This is the documented behaviour of reverse.
    In scalar context, concatenates the elements of LIST and returns a string value with all characters in the opposite order.
Re: reverse function
by jethro (Monsignor) on Jun 29, 2012 at 12:02 UTC

    This is a simple RTFM. Do 'perldocs -f reverse' and just read the second sentence where you are told what reverse does in scalar context

      Right , like perldoc -f reverse says

      print join(", ", reverse "world", "Hello"); # Hello, world
      print scalar reverse "dlrow ,", "olleH"; # Hello, world

       <tt><b>[doc://perldoc]</b> -f [doc://reverse]</tt> says

Re: reverse function
by uday_sagar (Scribe) on Jun 29, 2012 at 12:28 UTC

    Hi Sandyyy123

    You can visit this page and can read the first para.

    You get the expected result without "scalar" in your code.

    print (reverse(1,"ab"));