Search code examples
arraysperlhashperl-data-structures

Perl: Hash within Array within Hash


I am trying to build a Hash that has an array as one value; this array will then contain hashes. Unfortunately, I have coded it wrong and it is being interpreted as a psuedo-hash. Please help!

my $xcHash       = {};
my $xcLine;

#populate hash header

$xcHash->{XC_HASH_LINES} = ();

#for each line of data
    $xcLine       = {};

    #populate line hash

    push(@{$xcHash->{XC_HASH_LINES}}, $xcLine);

foreach $xcLine ($xcHash->{XC_HASH_LINES})
    #psuedo-hash error occurs when I try to use $xcLine->{...}

Solution

  • $xcHash->{XC_HASH_LINES} is an arrayref and not an array. So

    $xcHash->{XC_HASH_LINES} = ();
    

    should be:

    $xcHash->{XC_HASH_LINES} = [];
    

    foreach takes a list. It can be a list containing a single scalar (foreach ($foo)), but that's not what you want here.

    foreach $xcLine ($xcHash->{XC_HASH_LINES})
    

    should be:

    foreach my $xcLine (@{$xcHash->{XC_HASH_LINES}})