Monday, 9 November 2009

Perl Hash

A hash is a simple collection of keys and their corresponding values. The values can be homogeneous or heterogeneous data types.

Example :

%hash = (
key1 => 'value1',
key2 => 'value2',
key3 => 'value3',

Add a key/value pair to a hash :

In the solutions below, quotes around the keys can be omitted when the keys are identifiers.


$hash{ 'key' } = 'value'; # hash
$hash{ $key } = $value; # hash, using variables

Hash reference:

$href->{ 'key' } = 'value'; # hash ref
$href->{ $key } = $value; # hash ref, using variables

You can also store references to functions in your data structures, just as you can store references to arrays or hashes:

%HoF = ( # Compose a hash of functions
exit => sub { exit },
help => \&show_help,
watch => sub { $watch = 1 },
mail => sub { mail_msg($msg) },
edit => sub { $edited++; editmsg($msg); },
delete => \&confirm_kill,

if ($HoF{lc $cmd}) { $HoF{lc $cmd}->() } # Call function
else { warn "Unknown command: `$cmd'; Try `help' next time\n" }

In the second to last line, we check whether the specified command name (in lowercase) exists in our "dispatch table", %HoF. If so, we invoke the appropriate command by dereferencing the hash value as a function and pass that function an empty argument list. We could also have dereferenced it as &{ $HoF{lc $cmd} }(), or simply $HoF{lc $cmd}().

No comments:

Post a Comment

Tweets by @sriramperumalla