2

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?

1
  • There is no array in your code. Which variable do you think is an array? Commented Feb 10, 2016 at 22:03

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.