zigma
zigma

Reputation: 21

Hash variable and array in perl is giving an awkward output

I have just started with Perl scripting, while making an array and and fetching it from the hash variable. I am getting an awkward output.

Code is here:

%name= ( "xyz",1 ,"is",2, "my",3,"name",4);
%copy=%name;
$size=%name;
print " your rank is : $copy{'xyz'}";
print " \n";
print " the size of the array is : $size";

output is coming as :

your rank is : 1 
 the size of the array is : 3/8

why is the size of the array is of 3/8?

Upvotes: 2

Views: 53

Answers (2)

Zbynek Vyskovsky - kvr000
Zbynek Vyskovsky - kvr000

Reputation: 18825

It is internal information about the hash, please check the perl documentation:

If you evaluate a hash in scalar context, it returns false if the hash is empty. If there are any key/value pairs, it returns true; more precisely, the value returned is a string consisting of the number of used buckets and the number of allocated buckets, separated by a slash. This is pretty much useful only to find out whether Perl's internal hashing algorithm is performing poorly on your data set.

So here specifically it means that you have 8 buckets allocated in the hash and three of them are used.

To get the size use:

$size = keys %hash; # scalar is implicit here
print(scalar keys %hash);

Upvotes: 4

fugu
fugu

Reputation: 6568

If you want to find out the number of keys/values by using scalar keys:

my %name= ( "xyz",1 ,"is",2, "my",3,"name",4);

my %copy = %name;

my $size = scalar keys %name;

print "your rank is : $copy{'xyz'}\n";
print "the size of the array is : $size\n";

Upvotes: 2

Related Questions