FreeKB - Perl (Scripting) Hash (count keys and values)
Perl (Scripting) - Hash (count keys and values)

In Perl, there are 3 different kinds of hashes.

  • A regular hash, which is defined by the % and ( ) characters - %hash = ( );
  • A reference hash, which is defined with the $ and { } characters = $hash = { };
  • A hash array, which is defined with the % and [ ] characters - %hash = [ ];

 

Empty hash

Let's say you have the following empty hash that contains no keys and no values.

my %hash;

 

The following can be used to print the number of keys and values in the hash.

my $keys   = keys %hash;
my $values = values %hash;
print "keys   = $keys \n";
print "values = $values \n";

 

Which should return the following.

keys = 0
values = 0

 


Hash with keys and values

Let's append some keys and values. In this example, the hash has three keys (employee, id, department) and three values (John Doe, 123456, Engineering)

my %hash;
$hash{employee}   = "John Doe";
$hash{id}         = "123456";
$hash{department} = "Engineering";

 

Print the number of keys and values in the hash.

my $keys   = keys %hash;
my $values = values %hash;
print "keys   = $keys \n";
print "values = $values \n";

 

Which should return the following.

keys = 3
values = 3

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter 413a4 in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |