Perl: Hashes

By Eric Downing. Filed in Perl, Scripting, Utilities  |  
TOP del.icio.us digg

Here are some basics about Perl hashes that can be helpful to be used when an you need to associate a label with some value such as for names and telephone numbers or account numbers with amounts owed.

Create a hash variable.

my %hashvar;

Create a hash reference

my $refhash = {};

Add a value to a hash variable.

$hashvar{'somekey'} = 'someval';

Add a value to a hash reference.

$hashref->{'somekey'} = 'someotherval';

Access a value in a hash.

print $hashvar{'somekey'};

Access a value in a hash reference.

print $hashref->{'somekey}';

Access all Keys in a hash variable.
foreach my $k (keys(%hashvar))
{
print $hashvar{$k};
}

Access all Keys in a hash reference.

foreach my $k (keys(%$hashref))
{
  print $k . "n";
}

Access all Keys and values in a hash.

while (my ($key,$value) = each %hashvar)
{
  print "Key: " . $key . " has value:" . $value . "n";
}

Access all Keys and values in a hash.

while (my ($key,$value) = each %$refhash)
{
  print "Key: " . $key . " has value:" . $value . "n";
}

Assigning multiple values to a hash

%hasvar = (
  'test2' => 'myval',
  'test3' => 'myval3'
);

Note: This will clear the existing hash.

Delete a value from a hash

delete $hashvar{'key1'};

Delete a value from a hash reference.

delete $hashref->{'key1'};

Tags: , , ,

Leave a Reply