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


In reply to Re: Trying to understand hashes (in general) by FloydATC
in thread Trying to understand hashes (in general) by james28909

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.