Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: Trying to understand hashes (in general)

by FloydATC (Deacon)
on Dec 23, 2014 at 08:30 UTC ( [id://1111154]=note: print w/replies, xml ) Need Help??


in reply to Trying to understand hashes (in general)

I am trying my best to understand exactly how to add just a key without a value to a hash.

Although not actually very useful in the real world, this can be accomplished by simply assigning undef to a hash key. The key will then exist:

my %hash = (); $hash{'foo'} = undef; if (exists $hash{'foo'}) { print "The key 'foo' exists.\n"; } else { print "The key 'foo' does not exist.\n"; } if (defined $hash{'foo'}) { print "The key 'foo' is defined.\n"; } else { print "The key 'foo' is undefined.\n"; } if ($hash{'foo'}) { print "The key 'foo' is true.\n"; } else { print "The key 'foo' is false.\n"; }
What I am going to eventually shoot for, is making a hash of hashes

To accomplish this, you would make the value of your outer hash (of hashes) a reference to the inner hash, like so:

my %inner_hash = ( dir => '/tmp/foo/', filename => 'bar.txt' ); my %hash_of_hashes = (); $hash_of_hashes{'baz'} = \%inner_hash; # Backslash = reference to print "The filename associated with 'baz' is " .$hash_of_hashes{'baz' +}->{'filename'} . "\n";

Or you could use references all the way to begin with: (Notice the curly brackets)

my $entry = { firstname => 'Ola', lastname => 'Nordmann' }; my $staff = {}; my $id = 123; $staff->{$id} = $entry; printf( "%d: %s, %s\n", $id, $staff->{$id}->{'lastname'}, $staff->{$id}->{'firstname'} );
-- FloydATC

Time flies when you don't know what you're doing

Replies are listed 'Best First'.
Re^2: Trying to understand hashes (in general)
by james28909 (Deacon) on Dec 23, 2014 at 11:30 UTC
    Thanks for the thorough examples.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (4)
As of 2024-03-29 05:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found