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'} );
Time flies when you don't know what you're doing
In reply to Re: Trying to understand hashes (in general)
by FloydATC
in thread Trying to understand hashes (in general)
by james28909
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |