in reply to Re: Map Vs Foreach
in thread Map Vs Foreach

They both "visit" each element of a list (I would say, they both execute a block of code for each element of a list). The main difference is that for is a statement, map is an expression. As such, map has (in non-void context) a return value.

Only if you assign the return value of map to an array, and you have the same array as input list to the map, one could say that map 'transforms' a list. But then it's the combination of map and the assign statement.

The only way I can think of map on its own "transforming" a list is constructs like:

map {$_ = ucfirst} @array;
But for knows that trick as well:
for (@array) {$_ = ucfirst}

Replies are listed 'Best First'.
Re^3: Map Vs Foreach
by ikegami (Patriarch) on Nov 26, 2009 at 22:59 UTC

    The both "visit" each element of a list

    I was talking about their purpose.

    The only way I can think of map on its own "transforming" a list is constructs like:

    The whole purpose of map is to transform a list.

    my @b = map uc, @a; # 1 to 1 my @b = map { $_ => uc($_) } @a; # 1 to N, const ratio my @b = map { /^#/ ? () : $_ } @a; # 1 to N

    But then it's the combination of map and the assign statement

    No way. You don't have to assign the list to anything. You could pass it to join, for example.

    print join '|', map uc, qw( a b c );
      In my dictionary, that's as much "transforming" as addition "transforms" scalars. For me, something that doesn't change, isn't transforming - it's static.
        Are you confusing list and array? I didn't ask sooner since I know you understood the different before. But what you say doesn't make sense otherwise.
        A reply falls below the community's threshold of quality. You may see it by logging in.