Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

(jeffa) Re: re-using a hash reference (was: Mar)

by jeffa (Bishop)
on Jun 08, 2002 at 15:25 UTC ( [id://172790]=note: print w/replies, xml ) Need Help??


in reply to re-using a hash reference (was: Mar)

Depending upon your needs, sometimes you can get by with just:
$hash2->{'bob'} = $hash1->{'a'}->{'b'}->{'c'};
If you check for a defined key named 'bob' in $hash2, you will get a false value - however, if you check for a key named 'bob' that exists in $hash2, you will get a true value. So if you can get by with keys that have no values then don't bother with an if expression. If you can't, then do what vladb suggests (with Juerd's modification, of course).

Keep in mind that even checking for the presence of a hash key that does not exist will auto-vivify it into existence. Run the following code to see an example:

use strict; use Data::Dumper; my ($hash1,$hash2); $hash2->{'bob'} = $hash1->{'a'}->{'b'}->{'c'}; print Dumper $hash1, $hash2;

jeffa

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)

Replies are listed 'Best First'.
The Two Auto-Vivifies
by Util (Priest) on Jun 08, 2002 at 20:26 UTC
    Keep in mind that even checking for the presence of a hash key that does not exist will auto-vivify it into existence.

    Almost :)
    Perl will auto-vivify the hashes/hashkeys *necessary* to evaluate an expression.

    This will clarify the differences:

    perl -MData::Dumper -we 'print Dumper $h1 unless $h1->{a}->{b}->{c}' $VAR1 = { 'a' => { 'b' => {} } };
    In order to test for $h1->{a}->{b}->{c} there must exist a hash for 'c' to be a key in, so Perl auto-vivifies the data structure up to that point. But notice that 'b' points to an empty hash; 'c' is not a key in it! Perl sees that 'c' is not in {'b'}, and that is all that it needs to evaluate the unless.

    perl -MData::Dumper -we 'print Dumper $h1 for $h1->{a}->{b}->{c}' $VAR1 = { 'a' => { 'b' => { 'c' => undef } } };
    Here, we asked Perl to actually *obtain* the value stored in 'c', so Perl went one step further to create the hash key 'c', which holds 'undef', which it returns to the for statement.

Log In?
Username:
Password:

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

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

    No recent polls found