Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print a hash structure in Perl?

Tags:

hash

perl

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?

like image 456
Sourabh Avatar asked Mar 12 '10 07:03

Sourabh


People also ask

How do I view a hash element in Perl?

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..

How do I reference a hash in Perl?

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.

How do I undef a hash in Perl?

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);


1 Answers

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 :)

like image 124
Duncan Avatar answered Oct 02 '22 23:10

Duncan