"Perl for Perl Newbies" - Part 2HashesHash-Related Functions

2.1. Hash-Related Functions

delete

delete can be used to remove a key or a set of keys out of a hash. For example:

$myhash{
"hello"
} =
"world";
$myhash{
"perl"
} =
"TMTOWTDI";
$myhash{
"shlomi"
} =
"fish";

if (
exists(
$myhash{
"perl"
}))
{

print
"The key perl exists!
\n
";
}
else
{

print
"The key perl does not exist!
\n
";
}

delete(
$myhash{
"perl"
});

if (
exists(
$myhash{
"perl"
}))
{

print
"The key perl exists!
\n
";
}
else
{

print
"The key perl does not exist!
\n
";
}

The Comma Regarding Hashes

The comma can be used to combine two arrays into one larger one. Given the fact that a mini-hash with one key and one value can be specified using the $key => $valuenotation (which is essentially equivalent to $key, $value) a hash can be initialized in one statement.

Here's an example:

%hash1 = (

"shlomi" =>
"fish",

"orr" =>
"dunkelman",

"guy" =>
"keren"
    );

%hash2 = (

"george" =>
"washington",

"jules" =>
"verne",

"isaac" =>
"newton"
    );

%combined = (
%hash1,
%hash2);

foreach
$key (
keys(
%combined))
{

print
$key,
" = ",
$combined{$key},
"
\n
";
}

If the two combined hashes contain several identical keys, then the values of the latter hash will win.


Written by Shlomi Fish