Perl: Hash: Printing all elements of hash.

use strict;
use Data::Dumper; #needed for #dumper subroutine.

# Printing all elements of #a hash one by one.
my %main1 = (
“name” => “Kedar” ,
“surname” => “Kulkarni”,
“ID” => 1,
) ;
my $key; my $value;

while ( ($key,$value)=each (%main1) )  #using while loop
{ print “$key is $main1{$key} \n”;}

foreach $key (keys %main1)  # using foreach loop
{ print “\n $key is $main1{$key} \n” ;}

print Dumper(\%main1) ; #use of perl’s #inbuilt dumper subroutine.

Advertisements

Tags: , , ,

3 Responses to “Perl: Hash: Printing all elements of hash.”

  1. koolkedar Says:

    Output of the above program is:

    ID is 1
    name is Kedar
    surname is Kulkarni

    ID is 1

    name is Kedar

    surname is Kulkarni
    $VAR1 = {
    ‘ID’ => 1,
    ‘name’ => ‘Kedar’,
    ‘surname’ => ‘Kulkarni’
    };

  2. koolkedar Says:

    It is very important to see the use of curly brackets {} when referencing a single element from hash.
    Like , $main1{$key}.
    Many beginners forget to note this and consider regular brackets ().

  3. koolkedar Says:

    When printing single element from hash:
    You can use following 2 ways:

    ——————————————————————-
    print “Single element :”, $main1{name},” \n”;
    print “Single element :”, %main1->{surname},” \n”;
    ——————————————————————-

    Which will give the output as,

    Single element :Kedar
    Single element :Kulkarni

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s


%d bloggers like this: