in reply to Map Vs Foreach

Who case about speed, they don't do the same thing. map transforms a list and for visits each element of a list.

Replies are listed 'Best First'.
Re^2: Map Vs Foreach
by JavaFan (Canon) on Nov 26, 2009 at 21:04 UTC
    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}

      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.
          A reply falls below the community's threshold of quality. You may see it by logging in.