Hello Monks! I am trying my best to understand exactly how to add just a key without a value to a hash. I understand very little when it comes to hashes, and I am trying to get away from using arrays, because it is to my understanding that finding a certain key in a hash is much quicker than finding an element in an array if you have a huge amount of elements.

So what i was planning on doing was migrating a few of my scripts to use hashes instead of arrays. Here is the code i have (which works) but i am uncertain as to how it works tbh.
use warnings; use strict; my $path = shift; opendir( my $DIR, $path ); my %dirs; while ( my $file = readdir($DIR) ) { next if ( $file eq '.' || $file eq '..' ); $dirs{$file} = $file; } print "$_\n" for sort keys %dirs; #print "$_\n" for sort values %dirs; #same as keys... #print "$_\n" for sort %dirs;
This will read a directory of course, and will print out that directories contents whether it be file or directory. Also, if you comment out the first print statement, and uncomment the last print statement, it will print duplicates and i am unsure as to why it is adding the filename to key and value of the hash.

Any insight into this would be very much appreciated and thanks.

EDIT: What I am going to eventually shoot for, is making a hash of hashes. and in each of these hash of hashes will be directories and filenames respectively, so any input on that would be appreciated as well. :)

In reply to 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.