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?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.
Similar Threads
  1. Chris

    Algorithm for growing arrays

    Chris, Aug 8, 2006, in forum: Java
    Replies:
    11
    Views:
    1,864
    bugbear
    Aug 9, 2006
  2. Philipp
    Replies:
    21
    Views:
    1,734
    Philipp
    Jan 20, 2009
  3. rp
    Replies:
    1
    Views:
    1,055
    red floyd
    Nov 10, 2011
  4. Adam Akhtar
    Replies:
    5
    Views:
    941
    Adam Akhtar
    Mar 25, 2008
  5. Srijayanth Sridhar
    Replies:
    19
    Views:
    1,137
    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:
    1,012
    Älphä Blüë
    Jul 18, 2009
  7. Tore Aursand
    Replies:
    3
    Views:
    859
    Anno Siegel
    Sep 16, 2003
  8. Lynn

    Accessing Hash of hash of arrays

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