Wednesday, April 13, 2011

How to Find the Size of a Hash Reference in Perl

use strict;
use warnings;

# --- 1. Getting the size of a standard Hash ---
my %hash = (
    'apple'  => 1,
    'banana' => 2,
    'cherry' => 3
);

# The keys() function returns the number of elements when used in a scalar context.
# The string concatenation operator (.) automatically provides this scalar context.
print "Size of standard hash: " . keys(%hash) . "\n";


# --- 2. Getting the size of a Hash Reference ---
my $hash_ref = {
    'foo' => 'bar',
    'baz' => 'qux'
};

my $i = 0;

# Method A: Explicit scalar context using the 'scalar' keyword (often considered more readable)
$i += scalar keys %$hash_ref; 

# Method B: Implicit scalar context (the numeric '+=' operator forces scalar context)
$i += keys %$hash_ref;        

print "Size of hash reference (counted twice): $i\n";

No comments: