Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Generating Hash-of-List using map?

by moritz (Cardinal)
on Sep 23, 2013 at 16:29 UTC ( #1055329=note: print w/ replies, xml ) Need Help??


in reply to Generating Hash-of-List using map?

There are two approaches: either you can add state information to the block of the map, in which case writing it as an ordinary for-loop is probably much less confusing. Or you can do a separate reduction step which keeps the state for you.

Perl 5 is well suited for the first approach, so here it is:

use warnings; use strict; use Data::Dumper; my @CELLS=( 'A-1', 'A-2', 'A-3', 'A-4', 'B-5', 'B-6', 'C-7', 'C-8'); my %hash; for (@CELLS) { /^(.*)-(\d+)$/ and push @{ $hash{$1} }, $2 } print STDERR "hash DUMPER:\n", Dumper(\%hash), "\n";

The second approach becomes much easier when you have objects for pairs, so it's easier to pass them around as a scalar. Here is a Perl 6 implementation:

use v6; my @CELLS= 'A-1', 'A-2', 'A-3', 'A-4', 'B-5', 'B-6', 'C-7', 'C-8'; my %hash; %hash.push: @CELLS.map: *.split('-'); say %hash.perl;

If you think that's cheating, because Hash.push does all the heavy work, here is a version which doesn't use it:

use v6; my @CELLS= 'A-1', 'A-2', 'A-3', 'A-4', 'B-5', 'B-6', 'C-7', 'C-8'; my %hash = @CELLS.map({ my ($k, $v) = .split('-'); $k => $v})\ .categorize(*.key)\ # group by key .map({; .key => [.value>>.value]}) # list of pairs t +o list of values ; say %hash.perl;

(Updated to add the Perl 6 stuff).


Comment on Re: Generating Hash-of-List using map?
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (6)
As of 2014-07-30 00:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (229 votes), past polls