Perl Hashes



Hash Tables - Introduction



Creation, Access Elements, Existence, Adding Element

     # Create a hash table of state capitals

     %caps = ( 
        va => 'richmond',  # Keys are strings by default
        nc => 'raleigh'
             );

     # Print an element
     # Notice the $ and {}

     print $caps{'va'};    # prints richmond


     # Check if an element exists in the table

     exists $caps{'va'};   # evaluates to 1  (ie true)
     exists $caps{'VA'};   # evaluates to "" (ie false)


     # Add an element to the table

     $caps{'tn'} = 'nashville',
     print $caps{'tn'};   # prints nashville


Removing an Entry

     # Two ways to remove an entry:

       $caps{'nc'} = undef;

       delete $caps{'nc'};
        


Other Creation Methods

     # Another way to create the table of capitals

     %caps2 = ( 'va',  'richmond', 'nc', 'raleigh');
     print $caps2{'va'};   # prints richmond


     # Yet another way to create the table of capitals
     # Remember qw is quoteword

     %caps3 = qw( va   richmond nc raleigh);
     print $caps3{'va'};   # prints richmond

     print join ", ", %caps;  # va, richmond, nc, raleigh, tn, nashville
        


Accessing all Pairs: Function each

     %caps = ( 
        va => 'richmond',  # Keys are strings by default
        nc => 'raleigh',
        tn => 'nashville'
             );


    # Prints values in sequence.  
    #   function each returns each pair in table.

    while ( ($state, $cap) = each %caps)
    {
        print "$state, $cap"; 
    }


Accessing all Keys: Function keys

    # Prints pairs in table, sorted by key (ie state)
    #   function keys returns a list of the table's keys

    foreach  $state (sort keys   %caps) 
    {
        print "$state, $caps{$state} "; 
    }


Accessing all Values: Function values

    # Prints all values in table

    foreach  $aCap (sort values   %caps) 
    {
        print "$aCap "; 
    }


Lookup by Value: Must invert table