beckah beckah - 1 year ago 122
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,


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

However, when I call the function as
, 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 Source

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]};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download