Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

Re: Can a single key have different value assigned to it

by sundialsvc4 (Abbot)
on Apr 19, 2012 at 12:33 UTC ( #965936=note: print w/replies, xml ) Need Help??

in reply to Can a single key have different value assigned to it

You will need to define, say, an array(ref) of hash(refs), or vice-versa as you prefer.   This can be done more easily than you might suppose, thanks to Perl’s so-called “auto-vivication” features.   Consider the following two “Perl one-liner” examples:   (the command, followed by its output)

$ perl -e 'my $h; my $k="foo"; push @{$$h{k}}, "bar"; use Data::Dumper +; print Data::Dumper->Dump([$h], ["h"]);' $h = { 'k' => [ 'bar' ] };
or ...
$ perl -e 'my $h; my $k="foo"; push @{$$h{k}{"name"}}, "bar"; use Data +::Dumper; print Data::Dumper->Dump([$h], ["h"]);' $h = { 'k' => { 'name' => [ 'bar' ] } };

In each case, you can see that, simply as a matter of due course while executing a push statement, the entire data structure to which I intended to push the value simply “came to life automatically” as-needed if it didn’t exist already.   Since in this simple case nothing existed, this is what happened:

  • $h simply became a hashref;
  • It simply acquired the key “k”, and in the second case, nested hashrefs;
  • The entry simply became an empty arrayref, and a value was pushed onto it.

You don’t have to bother to consider, “well, does it exist yet?”   If you need it, and it doesn’t yet, then presto!, it does.   Not quite “let there be light, and there was light,” but pretty darned close.   This is one of the many reasons why Perl is so often called the Swiss Army® Knife of pragmatic data processing.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://965936]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (2)
As of 2018-02-19 02:23 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (257 votes). Check out past polls.