beckah beckah - 4 months ago 15
Perl Question

Pass nested hash to subroutine

I have a multidimensional hash that looks like the following:

my %hashTable;
$hashTable{'1'}{'A'} = "red";
$hashTable{'1'}{'B'} = "blue";
$hashTable{'2'}{'A'} = "orange";
$hashTable{'2'}{'B'} = "purple";


I want to pass an inner hash as an argument to a subroutine.
For instance,

hashFunc($hashTable{'2'});

sub hashFunc{
my %innerHash = $_[0];
}


However, when I call the function as
hashFunc($hashTable{'2'})
, I receive the error

Reference found where even-sized list expected


How do I properly provide an inner hash as an argument to a subroutine?

Answer

Multi-dimensional data structures are assembled via reference.

$hashtable{'2'} is a scalar value, that's reference to a hash.

To use it in a subroutine, you need to dereference it - either before sending it:

hashFunc( %{$hashtable{'2'}});

Which will send a list of values (that you can then assign into a hash as you do).

Or within the hash:

 my %innerHash = %{$_[0]};
Comments