Re: growing hash of arrays

Discussion in 'Perl' started by Joe Woodhouse, Jan 20, 2010.

  1. Hi there,

    Unless I'm misunderstanding you, I think that can all be replaced with just

    push @{$hash{$key}}, $value;

    There's no need to check whether the key is already defined. I wrote this
    script to demonstrate

    # SCRIPT
    ###############################
    use strict;
    use warnings;
    use Data::Dumper;

    my (%hash);

    sub func{
    my($key,$val) = @_;
    push @{$hash{$key}}, $val;
    }

    func('testkey1','testval1');
    func('testkey1','testval2');
    func('testkey2','testval3');
    print Dumper %hash;

    # OUTPUT
    ###############################
    $VAR1 = 'testkey1';
    $VAR2 = [
    'testval1',
    'testval2'
    ];
    $VAR3 = 'testkey2';
    $VAR4 = [
    'testval3'
    ];

    Cheers
    Joe.

    "HASM" <> wrote in message
    news:m3hbwarpqd.fsf@127.0.0.1...
    >
    > I've have this sequence in several of my scripts:
    >
    > if (defined $hash{$key}) {
    > push (@{$hash{$key}}, $value);
    > } else {
    > my @array = ($value);
    > $hash{$key} = \@array;
    > }
    >
    > There's got to be a more compact way of writing this!
    >
    > -- HASM
     
    Joe Woodhouse, Jan 20, 2010
    #1
    1. Advertisements

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Chris

    Algorithm for growing arrays

    Chris, Aug 8, 2006, in forum: Java
    Replies:
    11
    Views:
    1,840
    bugbear
    Aug 9, 2006
  2. Philipp
    Replies:
    21
    Views:
    1,645
    Philipp
    Jan 20, 2009
  3. rp
    Replies:
    1
    Views:
    954
    red floyd
    Nov 10, 2011
  4. Adam Akhtar
    Replies:
    5
    Views:
    898
    Adam Akhtar
    Mar 25, 2008
  5. Srijayanth Sridhar
    Replies:
    19
    Views:
    1,070
    David A. Black
    Jul 2, 2008
  6. Älphä Blüë

    Hash of Hash of Arrays Question

    Älphä Blüë, Jul 18, 2009, in forum: Ruby
    Replies:
    5
    Views:
    968
    Älphä Blüë
    Jul 18, 2009
  7. Tore Aursand
    Replies:
    3
    Views:
    812
    Anno Siegel
    Sep 16, 2003
  8. Lynn

    Accessing Hash of hash of arrays

    Lynn, Feb 14, 2005, in forum: Perl Misc
    Replies:
    9
    Views:
    804
    Alan J. Flavell
    Feb 16, 2005
Loading...