Cool_Coder
Cool_Coder

Reputation: 5073

Unable to create Hash in Perl?

I am learning Perl Script from here. I am having problem creating Hash. The code is here:

print "Hello World!\n";
@days = ("1", "2");
print "There are $#days days\n";
print "1 is $days[0]\n";
%months = ("a" => 1, "b" => 2, "c" => 3);
print "There are $#months keys\n";
print "a is $months[0]\n";
for $i (keys %months)
{ print "$i has value $months[$i].\n"}

Now its working fine with the array. But for Hash its printing "There are -1 keys". Also its not printing anything for the variable values in last to print calls.

Upvotes: 1

Views: 231

Answers (3)

TLP
TLP

Reputation: 67900

You are using the array syntax on a hash, which does not do what you think at all. Instead of operating on your hash, you are operating on an array called @months. For example:

print "There are $#months keys\n";

This will look for the array @months, see that it is empty, and happily print -1.

When you do

for $i (keys %months) { 
    print "$i has value $months[$i].\n"
}

Perl will try to convert the keys a, b and c to numbers, which will be 0. This will issue a warning:

Argument "a" isn't numeric in array element ...

Then it will print the empty array element $month[0]. Which will issue an undefined value warning. You do not get these warnings, because you did not use

use strict;
use warnings;

In your script. strict would have told you that @months has not been declared, and stopped this bug right away.

The syntax you should have used is:

print "There are " . (keys %months) . " keys\n";
...
print "$i has value $months{$i}\n";

Upvotes: 6

Zaid
Zaid

Reputation: 37136

In Perl, accessing elements in a hash use a slightly different syntax to arrays. Use curlies for hashes, square brackets for arrays:

print "a is $months{a}\n";  # "a is 1"

And $#months is another way of saying 'last index of @months', when what you really meant was to count the number of keys in %months:

printf "There are %d keys\n", scalar keys %months;

If you insist on print instead of printf:

print "There are $#{[keys %months]} keys\n";

(but maybe it's a few steps ahead of where you want to be at the moment)

Upvotes: 3

tauli
tauli

Reputation: 1420

$#months and $months[0]refer to an array and not a hash. You access the value of a hash by using curly braces $months{key}.

Also, you should use strict; and initialize variables with my(). If you had done that, you would have gotten a compiler error that @months does not exist.

Upvotes: 0

Related Questions