Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

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.


Comment on Re: Can a single key have different value assigned to it
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (6)
As of 2014-12-21 02:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (101 votes), past polls