in reply to Re: Using s///e and it just doesn't feel right
in thread Using s///e and it just doesn't feel right

map should not be used in a void context, that's why foreach is there.

map { print "$_\n" } (@array);
foreach (@array) { print "$_\n" }

These are functionally the same, but map generates a return value that can be assigned to another array, and foreach does not, therefore map is not appropriate. Instead it should be used for its return value:

@squares = map { $_ * $_ } (@array);

The above code with foreach would have to be:

foreach (@array) { push @squares, $_ * $_ }

Replies are listed 'Best First'.
Re: Re: Re: Using s///e and it just doesn't feel right
by perlguy (Deacon) on Jun 20, 2003 at 20:13 UTC

    When the map function is used as you suggest above, it is being called in void context, which I agree is not as good as for. Having said that, I would suggest that a more perlish idiom of saying the above would not require calling map in void context at all:

    print map "$_\n", @array;

    And better still:

    print join "\n", @array;

    Just some thoughts.

Re: Re: Re: Using s///e and it just doesn't feel right
by waswas-fng (Curate) on Jun 20, 2003 at 16:28 UTC
    map should not be used in a void context, that's why foreach is there.

    And why then is map allowed to be called in void context? =)

    -Waswas
      It is addressed in the Perl FAQ.

      There are a lot of things you can do with Perl that you shouldn't do.

        #!/usr/bin/perl use strict; sub bob { map { print "$_$/" } @_; } my @thing = qw(tom dick harry); bob(@thing); print "============$/"; my @results = bob(@thing); print "We printed " . (scalar @results) . " items$/";

        antirice    
        The first rule of Perl club is - use Perl
        The
        ith rule of Perl club is - follow rule i - 1 for i > 1

Re: Re: Re: Using s///e and it just doesn't feel right
by kral (Monk) on Jun 23, 2003 at 08:44 UTC
    These are functionally the same, but map generates a return value that can be assigned to another array, and foreach does not, therefore map is not appropriate.
    There are also situations where forech aren't appropriate. Like:

    foreach(@array){ push(@tmp, $_) if(/$regex/); }
    But I respect this way of coding 'cause TMOWTDI.
    ----------
    kral
    (sorry for my english)