Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Re: Creating hash of arrays (in a faster way)

by choroba (Chancellor)
on Nov 01, 2013 at 09:35 UTC ( #1060729=note: print w/replies, xml ) Need Help??

in reply to Creating hash of arrays (in a faster way)

You can use map to fix the first method.
@hash{@cols} = map [$_], @values;

The speed can be measured by Benchmark.

لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Replies are listed 'Best First'.
Re^2: Creating hash of arrays (in a faster way)
by Corion (Pope) on Nov 01, 2013 at 09:57 UTC

    I would assume from the data structure that the arrays might be intended to contain more than one value, although that has not been demonstrated in the code of the question.

    My approach, keeping with the spirit of the push as I perceive it, is below. It's less ugly than what I thought it would be:

    for my $row ( @hash{ @cols }) { push @$row, shift @values }

    I also thought about an approach that does avoid the loop, but my solutions only shuffles the loop around, and doing weirdo aliasing tricks through @_ did not lead to a good solution for me - it seems that array-assigning to the aliased @_ does not do individual assignment to the slots:

    sub alias { \@_ }; { my %hash; my @cols = qw(min max sum); my @values = qw(1 3 4); @{ alias map { $_->[ 0+ @$_ ] } @hash{ @cols } }= @values; print Dumper \%hash; }

    Avoiding the magic aliasing and passing around references does not really improve the situation, even though it works.

    { my %hash; my @cols = qw(min max sum); my @values = qw(1 3 4); for( map { \$_->[ 0+@$_ ] } @hash{ @cols } ) { $$_= shift @values; }; print Dumper \%hash; }
      You're correct. The arrays are indented to contain more than one value.
      Iterating over the values of the hash seems to be quite a bit faster. Thank you very much.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1060729]
[Corion]: But at least I have a plan of action to move the site to https, played some (free!) VR games with friends and watched the plans for the next German Perl workshop progress ;)
[Corion]: AltSpace VR is amazingly good - highly polished and with some of the games you get for free what you'd pay EUR 20 or EUR 40 otherwise
[Corion]: But maybe it's also due to that I play with friends, which makes a game more enjoyable anyway ;)
[Corion]: Oh - I released a new version of some module, thanks to a pull request. But I don't consider "update Makefile.PL" and "update author tests" as "writing code" ;-D

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (6)
As of 2017-08-21 09:26 GMT
Find Nodes?
    Voting Booth?
    Who is your favorite scientist and why?

    Results (319 votes). Check out past polls.