Wednesday, January 19, 2011

Hash Manipulation

keys() function
  • Returns a list containing all the keys of the hash
     
  • Calling keys() on an empty hash returns an empty list
     
  • The keys are not in any order: not sorted, not in order added, not nothin'.
     
  • Each keys in the list will be unique, because all keys in the hash are unique.
values() function
  • Partner of the keys() function
     
  • Returns a list containing all the values in the hash
     
  • Calling values() on an empty hash returns an empty list
     
  • The values are not in any order: not sorted, not in order added, not nothin'.
     
  • Values are not necessarily unique, because values in the hash don't have to be.
    my %stats;
    $stats{ "name" } = "Andy Lester";
    $stats{ "age" } = 31;
    
    @keys = keys %stats;
    # @keys is ( "name", "age" ), or maybe ( "age", "name" )
    
    @values = values %stats;
    # @values is ( "Andy Lester", 31 ) or maybe ( 31, "Andy Lester" )
Looping over hashes
  • To loop over a hash, get a list of keys, sort it, and loop on it
    my %stats;
    $stats{ "name" } = "Andy Lester";
    $stats{ "age" } = 31;
    my @keys = keys %stats;
    @keys = sort @keys;
    for my $key ( @keys ) {
        print "$key: ", $stats{ $key }, "\n";
        }
    # Prints:
    # age: 31
    # name: Andy Lester
Deleting hash entries
  • Use the delete() function to remove a hash entry
    my %stats;
    $stats{ "name" } = "Andy Lester";
    $stats{ "age" } = 31;
    delete $stats{ "name" };
    # %stats now has only one value
  • Note that you do NOT want to set the hash element to undef. The hash element will still exist, with a value of undef.

No comments: