Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Generating Hash-of-List using map?

by hdb (Parson)
on Sep 23, 2013 at 19:24 UTC ( #1055376=note: print w/ replies, xml ) Need Help??


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

All proposals are cheating so far! Here is what you are looking for (warning: dirty code!)

my %hash = map { /^([^-]*)-(.*)$/; if( $1 eq ($a//'-') ) { push @$b, $ +2; () } else { ( $a = $1 => $b = [ $2 ] ) } } @CELLS;

Of course, should $a accidentally be identical to the bit left of the hyphen in the first element of @CELLS, then it fails...

UPDATE: Small improvement on the else branch.


Comment on Re: Generating Hash-of-List using map?
Select or Download Code
Re^2: Generating Hash-of-List using map?
by LanX (Canon) on Sep 23, 2013 at 21:12 UTC
    I have the suspicion that this only works with sorted input while the "cheating propsosals" always work...

    DB<148> %hash=() DB<149> @CELLS => ("A-1", "A-2", "A-3", "A-4", "B-5", "B-6", "C-7", "C-8", "A-9") DB<150> %hash = map { /^([^-]*)-(.*)$/; if( $1 eq ($a//'-') ) { push + @$b, $2; () } else { ( $a = $1 => $b = [ $2 ] ) } } @CELLS; => ("B", [5, 6], "C", [7, 8], "A", [9])

    oops, indeed! ;-)

    Cheers Rolf

    ( addicted to the Perl Programming Language)

      Oh, #@%$"!

      I admit defeat. A sort is probably not what the OP specified. One could build a full temporary hash in the map but that would be cheating as well (also relies on $a not been used for anything else before):

      my %hash = map { /^([^-]*)-(.*)$/; exists $$a{$1}? (push(@{$$a{$1}},$2 +) and ()): ( $1=>$$a{$1}=[$2] ) } @CELLS;

      So there is really no way around first declaring the hash and then filling it. What a pity!

        > So there is really no way around first declaring the hash and then filling it. What a pity!

        O come on! Just "cheat"! ;-)

        DB<113> @CELLS = ("A-1", "B-2", "C-3", "A-4", "B-5", "C-6", "A-7", " +B-8", "C-9") => ("A-1", "B-2", "C-3", "A-4", "B-5", "C-6", "A-7", "B-8", "C-9") DB<114> %hash = map { /^([^-]*)-(.*)$/; if( $1 eq ($a//'-') ) { push + @$b, $2; () } else { ( $a = $1 => $b = [ $2 ] ) } } sort @CELLS; => ("A", [1, 4, 7], "B", [2, 5, 8], "C", [3, 6, 9])

        Cheers Rolf

        ( addicted to the Perl Programming Language)

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (9)
As of 2014-08-23 04:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (172 votes), past polls