Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Parsing attributes in one line using map

by davidrw (Prior)
on Sep 25, 2006 at 12:44 UTC ( #574725=note: print w/replies, xml ) Need Help??


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 };

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://574725]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (7)
As of 2021-01-21 12:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?