in reply to map in void context

Others have already said that map returns a list, which is discarded in void context. It works like for and, like for, operates on an alias ($_) of each element of the list passed, so you can use it to edit list elements in-place.

But it constructs a list of results, and that list consumes memory:

perl -le '@l=0..2**16;$_++for@l; print `ps -o vsz= -p $$`*1024;print f +or @l[0..3]' 10723328 1 2 3 4 perl -le '@l=0..2**16;map{$_++}@l; print `ps -o vsz= -p $$`*1024;print + for @l[0..3]' 11771904 1 2 3 4

Also, the map variant is two chars longer than the for one, so you won't see Golfers using it in void context...

Replies are listed 'Best First'.
Re^2: map in void context
by Tanktalus (Canon) on Dec 18, 2008 at 04:12 UTC

    Not that I've checked, but I recall a rumour that modern-enough perls (5.8.8, maybe) detect map in a void context and drop the list creation to save time and space. I don't see a point: the definition of map is "Evaluates ... and returns the list" whereas foreach (aka for) "is an iterator: it executes the statement once for each item". So map should return a list (it has explicit documentation regarding scalar context), and for shouldn't really have a return (or an accumulator).

    And the map variant is actually only one char longer if you golf it right:

    $_++for@l map$_++,@l
    But I still prefer map for mapping, and for for iterating.