Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: "A meditation on Hashes", or "Why i need more aspirin"

by fireartist (Chaplain)
on Jun 16, 2006 at 12:54 UTC ( #555765=note: print w/replies, xml ) Need Help??


in reply to "A meditation on Hashes", or "Why i need more aspirin"

Maybe including the program output would be helpful, then point out which results you find surprising.

The results of defined() on "" or undef apply to any perl variable, not just hashes, and a hash key existing after being assigned "" or undef shouldn't really be that surprising.

After running this myself, the only outcome that I didn't expect, was that exists $hash{d} returns false after print $hash{d}. I had expected the print to autovivify the d key to contain undef.

Replies are listed 'Best First'.
Re^2: "A meditation on Hashes", or "Why i need more aspirin"
by xdg (Monsignor) on Jun 16, 2006 at 13:20 UTC
    After running this myself, the only outcome that I didn't expect, was that exists $hash{d} returns false after print $hash{d}. I had expected the print to autovivify the d key to contain undef.

    The thing to remember is that it is not hash values that autovivify -- it is anonymous hash and array references that autovivify. For example, given an undef scalar, you can autovivify the anonymous hash just by coding as if the scalar contained a hash reference:

    use strict; use warnings; local $\="\n"; my $hr; print '$hr ', defined $hr ? 'defined' : 'undefined'; print '$hr->{a} ', exists $hr->{a} ? 'exists' : 'doesn\'t exist'; print '$hr ', defined $hr ? 'defined' : 'undefined'; print '$hr is ', $hr;

    Prints:

    $hr undefined $hr->{a} doesn't exist $hr defined $hr is HASH(0x3d51c0)

    -xdg

    Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (2)
As of 2021-01-22 02:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?