Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: How to declare a hash of array?

by rhesa (Vicar)
on Sep 29, 2007 at 09:09 UTC ( [id://641681]=note: print w/replies, xml ) Need Help??


in reply to How to declare a hash of array?

That's easy, just declare it:
my %hash;
Perl will take care of the rest: it will create new keys on demand, and it'll also create the arrays on the fly. This process is called Autovivification.

Replies are listed 'Best First'.
Re^2: How to declare a hash of array?
by bart (Canon) on Sep 29, 2007 at 10:35 UTC
    But careful with mixed data structures and the risk of accidental symbolic references. strict can catch that.

    An example:

    my %hash; $hash{beta} = 'x'; for my $name ( qw(alpha beta) ) { push @{$hash{$name}}, 123, 456; } use Data::Dumper; print Dumper \%hash;
    Result:
    $VAR1 = { 'alpha' => [ 123, 456 ], 'beta' => 'x' };
    So... where's the array data for 'beta'? It's in the global variable @x. Witness: append this line to the above script:
    print Dumper \@x;
    Result:
    $VAR1 = [ 123, 456 ];

    With strict enabled, it'll get caught while trying to push the data: insert the line

    use strict;
    at the top of the script and comment out the line, dumping @x, we appended earlier:
    Can't use string ("x") as an ARRAY ref while "strict refs" in use at t +est.pl line 6.

    Nasty if you didn't expect it.

    The risk of running into it is greatest when using data structures of unequal depth.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (3)
As of 2024-04-16 13:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found