Operation on hash using Perl


-- Use reverse to invert a hash.
%inverted = reverse %hash;

-- order by key alphabetically
foreach my $key ( sort keys %hash )
{
print "key: " . $key . " value: " . $hash{$key} . "\n";
}

-- order by key numerically
foreach my $key ( sort { $a $b } keys %hash )
{
print "key: " . $key . " value: " . $hash{$key} . "\n";
}

-- Using 'keys' in a 'foreach' loop
foreach my $key ( keys %hash )
{
print "key: $key, value: $hash{$key}\n";
}

-- Using 'each' in a 'while' loop
This method has the advantage that it's possible to sort the output by key.
The disadvantage is that it creates a temporary list to hold the keys, in case your hash is very large you end up using lots of memory resources.

while ( ($key, $value) = each %hash )
{
print "key: $key, value: $hash{$key}\n";
}

-- check if a key exists in a hash
print "Key $key exists\n" if ( exists($hash{$key}) );

-- get the keys of a hash
@list = keys %hash;

-- get the values of a hash
@list = values %hash;

-- remove a hash element
delete $hash{"key"};

-- empty a hash
%hash = ();

Advertisements
Post a comment or leave a trackback: Trackback URL.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: