Anti-nuisance lawsuit warning: The purpose of these notes is to remind me, Zoegond, of stuff or to help me work stuff out. They may contain mistakes.

Quick

  • ($a, $b....) = unpack("A2A7...", $packed)
  • push( array, list )

Tuesday, March 6, 2012

Perl map and grep

map evaluates an expression (or block) for each member of a list in turn.

Each evaluation 'sees' $_ as set to the current list member.

The results of the applications are accumulated in a list, which map returns.

Eg

join(",", map $_ . " => " . $h{$_}, keys %h )


shows the members of a hash (map returns a list of strings which join agglutinates into a string).

In my experience the arguments to map should be left unparenthesised.

grep on the other hand evaluates the block/expression for each member of the list; the return value of grep is a list of the elements from LIST for which the block/expression returned a true value. (Or a count of those elements, in scalar context).

These two statements have the same result:

@out = grep {EXPR} @in;
@out = map { EXPR ? $_ : () } @in;


And a rough SQL metaphor:

map: select expr(item) from list
grep: select item from list where expr(item)=1

Followers

Blog Archive