Examples:
%hash = (2010 => 21, 2009=> 9);
$hash = {
a => {
0 => {test => 1},
1 => {test => 2},
2 => {test => 3},
3 => {test => 4},
},
};
How do I print the hash?
Hash variables are preceded by a percent (%) sign. To refer to a single element of a hash, you will use the hash variable name preceded by a "$" sign and followed by the "key" associated with the value in curly brackets..
Similar to the array, Perl hash can also be referenced by placing the '\' character in front of the hash. The general form of referencing a hash is shown below. %author = ( 'name' => "Harsha", 'designation' => "Manager" ); $hash_ref = \%author; This can be de-referenced to access the values as shown below.
undef on hash elements The script uses $h{Foo} = undef; to set the value of a hash key to be undef. use strict; use warnings; use Data::Dumper qw(Dumper);
Do you want to print the entire hash, or specific key, value pairs? And what is your desired result? IF it's just for debugging purposes, you can do something like:
use Data::Dumper;
print Dumper %hash; # or \%hash to encapsulate it as a single hashref entity;
You can use the each
function if you don't care about ordering:
while ( my($key, $value) = each %hash ) {
print "$key = $value\n";
}
Or the for
/ foreach
construct if you want to sort it:
for my $key ( sort keys %hash ) {
print "$key = $hash{$key}\n";
}
Or if you want only certain values, you can use a hash slice, e.g.:
print "@hash{qw{2009 2010}}\n";
etc, etc. There is always more than one way to do it, though it helps to know what you're frying to do first :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With