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

hi, i'm at the exercises part of Chap3 of the llama book and i'm stuck with the reverse function. i have this script:
#!/usr/bin/perl use warnings; use strict; my $test = ''; $test = "apples"; print reverse $test;
it still prints out the word "apples" but not in the reverse way. i have tried using "@test" too but it doesn't reverse. appreciate your help.

Replies are listed 'Best First'.
Re: reverse is not reversing
by LanX (Saint) on Nov 26, 2018 at 13:13 UTC
    Print is imposing a list context.

    You need scalar context for string reverse

    print scalar reverse $test;

    What's happening is that the one element list is reversed now, which is of course useless.

    DB<5> print reverse qw/a1 b2 c3/ # inverting list c3b2a1 DB<6> print scalar reverse qw/a1 b2 c3/ # inverting string 3c2b1a

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

    update

    added code

      oh. it only works with more than one word. i thought it would reverse "apple" into "elppa".
        No, it will reverse "apple" into "elppa", but only in scalar context. Read more about context in the book Modern Perl.

        Update: Fixed the book title. Thanx LanX.

        ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
        > it only works with more than one word

        that's wrong, context matters (LHS) not input (RHS)

        DB<9> print reverse "text" # list context text DB<10> print scalar reverse "text" # scalar context txet DB<11> $a= reverse "text" # scalar DB<12> print $a # still print LIST, but $a is +already reversed txet

        Cheers Rolf
        (addicted to the Perl Programming Language :)
        Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

Re: reverse is not reversing
by 1nickt (Canon) on Nov 26, 2018 at 13:14 UTC

    Hi, reverse operates on lists:

    reverse LIST In list context, returns a list value consisting of the el +ements of LIST in the opposite order. In scalar context, concaten +ates the elements of LIST and returns a string value with all chara +cters in the opposite order. print join(", ", reverse "world", "Hello"); # Hello, w +orld print scalar reverse "dlrow ,", "olleH"; # Hello, w +orld Used without arguments in scalar context, "reverse" revers +es $_. $_ = "dlrow ,olleH"; print reverse; # No output, li +st context print scalar reverse; # Hello, world
    Add a call to scalar:
    #!/usr/bin/perl use warnings; use strict; my $test = ''; $test = "apples"; print scalar reverse $test;

    Hope this helps!


    The way forward always starts with a minimal test.