http://www.perlmonks.org?node_id=1055329


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).