Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

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: *.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 ={ 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).

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1055329]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (1)
As of 2018-04-20 02:08 GMT
Find Nodes?
    Voting Booth?