To print the values in a hash, use the keys keyword.
my %hash = ( 'a' => 1, 'b' => 2, 'c' => 3);
foreach (keys %hash) {
print "$_ => $hash{$_}\n";
}
Cheers. :-)
| [reply] [d/l] |
To print the values in a hash, use the keys keyword.
my %hash = ( 'a' => 1, 'b' => 2, 'c' => 3);
foreach (keys %hash) {
print "$_ => $hash{$_}\n";
}
Cheers. :-)
In general, I wouldn't say that. "keys" is a standard Perl function (not a keyword), of which you can omit the () because there is a prototype known for it. Furthermore:
- If you want the values of a hash in no particular order as a list, use the values function.
my @value = values %hash;
- If you want the keys of a hash in no particular order as a list, use the keys function.
my @key = keys %hash;
- If you want either the values or keys in a particular order, use sort() as well.
my @value = sort values %hash;
my @key = sort keys %hash;
foreach (sort keys %hash) {
print "$_ => $hash{$_}\n";
}
- If you want to show the keys and possibly the associated values in no particular order, use each.
while (my $key = each %hash) {
print "$key\n";
}
while (my ($key,$value) = each %hash) {
print "$key => $value\n";
}
The reason for using each() over keys(), is that keys() (and values()) build a list of the values. For large hashes, this list can get very big and cosume a lot of memory. You don't have that when you're using each(), as it will only fetch one key or one key/value pair from the hash at a time.
Liz
| [reply] [d/l] [select] |