in reply to Parsing attributes in one line using map

Returning more (or less even) elements than provided is very natural for map and very commonly used, especially for generating hashes .. here's two relatively trivial examples:
perl -MData::Dumper -le 'my %cubes = map { $_ => $_**3 } 1..4; print D +umper \%cubes' $VAR1 = { '1' => '1', '2' => '8', '3' => '27', '4' => '64' }; my @users = [ {id=>4324, name=>'blah'}, {id=>1234, name=>'stuff'}, {id +=>5678, name=>'foo'} ]; my %usersByName = map { $_->{id} => $_ } @users; my $id = prompt_for_user_id; my $user = $usersByName{$id};
Also, see map for more examples (including the basic hash creation), and this quote:
Evaluates BLOCK or EXPR in list context, so each element of LIST may produce zero, one, or more elements in the returned value.

Replies are listed 'Best First'.
Re^2: Parsing attributes in one line using map
by jhourcle (Prior) on Sep 25, 2006 at 13:38 UTC
    Returning more (or less even) elements than provided is very natural for map and very commonly used, especially for generating hashes ..

    For those not familiar with returning less -- use an empty list (). To build on davidrw's example:

    perl -MData::Dumper -le 'my %oddcubes = map { $_%2 ? ($_ => $_**3) : ( +) } 1..9; print Dumper \%oddcubes' $VAR1 = { '1' => 1, '3' => 27, '7' => 343, '9' => 729, '5' => 125 };