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.
     
    Joe Woodhouse, Jan 20, 2010
    #1
    1. Advertisements

Ask a Question

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.