Wednesday, June 4, 2008

Perl: Print from hash using each


Share at Facebook

I'm going to tell you how to print elements from a HASH using each keyword of Perl. I'll use the while loop, and combine the while with each to print the elements.

I'm giving two ways of printing, one is direct print, and another one is print using hash reference in case if you need to pass the hash to some other function. Just keep going through the code and comment, and you'll understand it easily.

use strict;

main_function();

## Lets say it is your main function
sub main_function{
## Declare the hash.
my %hash = ( "one" => 1,
"two" => 2,
"three" => 3,
"four" => 4,
"five" => 5
);

print "........1.non-ref.........\n";
## print without reference
while( my ($key, $value) = each(%hash) ){
print "$key : $value\n";
}

print "\n..........2.ref.......\n";
## print method using reference.
print_from_hash_reference(\%hash);
}

## Just for, if you need to use reference of hash
## Printing the key/vlaues from hash using ref
sub print_from_hash_reference{
my $hash_ref = shift;

## Takes each $key and $value from hash untill all finished
while( my ($key, $value) = each(%$hash_ref) ){
print "$key : $value\n";
}
}

If you need to know more about Perl, you can take a look at Perl related contents at http://icfun.blogspot.com/search/label/perl, Or you can search my blog for other Programming related contents.




No comments: