Perl Hash Maps

Perl Hash Maps/associative arrays


  • hash tables consist of key/value pairs
  • every key is followed by a value

    values can be assigned to hash tables as

      %states=  ("California","Sacramento","Wisconsin","Madison","New York","Albany");  

    We can also use => operator to identify the

    key to the left, and the value to the right; if the => operator

    encounters bare words in key positions, they will be automatically

    quoted (note “New York”, however, which consists of two words

    and MUST be quoted

      %states=  (California=>"Sacramento",Wisconsin=>"Madison","New York"=>"Albany");  

    In above example California is key and Sacromento is value.

    Similarily Wisconsin is key and Madison is value.


      print "Capital of California is " . $states{"California"} . "nn";  

    printing all values(using for loop):

      #!/usr/bin/perl  %states=  (California=>"Sacramento",Wisconsin=>"Madison","New York"=>"Albany");  foreach my $keys(keys %states)  {    print "KEY:$keys VALUE:$states{$keys}n";    }    output  KEY:Wisconsin VALUE:Madison  KEY:New York VALUE:Albany  KEY:California VALUE:Sacramento  
  • If you have found my website useful, please consider buying me a coffee below 😉