简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM