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

Dear monks,

I've got a problem with reverse in map:

C:\ce3\bin>perl -w my @list = qw(abc2 abc3 abc1 abc0); my @list2 = map { my $r = reverse($_); $r } @list; # scalar context print "@list2"; ^Z 2cba 3cba 1cba 0cba C:\ce3\bin>
The code above works as I want it to work: it reverses every element in the list as string. But this code below doesn't reverse the strings:
C:\ce3\bin>perl -w my @list = qw(abc2 abc3 abc1 abc0); my @list2 = map { reverse($_) } @list; print "@list2"; ^Z abc2 abc3 abc1 abc0
I think, in the second example, the reverse-function is somehow used in list-context, not in scalar context. Is this a perl bug, or am I the bug (as usual)?

I've run these codes under Activestateperl 631 (Win2k) and Perl 5.005_03 under Solaris.

Best regards,
perl -le "s==*F=e=>y~\*martinF~stronat~=>s~[^\w]~~g=>chop,print"

Replies are listed 'Best First'.
Re: Bug? with reverse in map
by ariels (Curate) on May 14, 2002 at 13:29 UTC

    map does, indeed, evaluate its BLOCK in list context. This is so you can say stuff like

    my $n=0; my %position = map {$_ => $n++} @list

    The simple fix is to make your block evaluate reverse in scalar context: map { scalar reverse($_) } @list.

      I'm appalled that the first thing I thought of to scalarify the return from reverse was:
      my @list2 = map { ~~reverse } @list;
      Too much golf!
Re: Bug? with reverse in map
by Joost (Canon) on May 14, 2002 at 13:31 UTC
    The interior subroutine / block in a map is called in list context, this is not a bug, as it allows for things like:
    %seen = map { $_ => 1 } qw( some list );
    and other (maybe more useful) things... </code>
    -- Joost downtime n. The period during which a system is error-free and immune from user input.