Mina Shaigan Mina Shaigan - 4 months ago 13
Perl Question

How do I access an array in an array of hash in perl?

I have an array of hash that one of the value of hash is an array .
-> I push "@title" to "part"
and for print ,
-> I put each of books{part} in a temporary array to access each element of title but it just print the first element
I can't access all element of "title" in array "books"

@books = ();
@title = (1,2,3,4,5);
push @books,{subject=>"hello" , part =>@title };
for($i=0;$i<scalar(@books);++$i)
{
print $books[$i]{subject};

@temp = $books[$i]{part};
for($j=0;$j<scalar(@temp);++$j)
{
print $temp[$j]; #this print just first element "1"
}
}

Answer

The problem here is that the Hash reference you are pushing on the @books array is not be created correctly.

The Hash reference you are creating looks like this:

 {  'subject' => 'hello',
    'part'    => 1,
    '2'       => 3,
    '4'       => 5,
 }

when you probably expected it to look like this:

{  'subject' => 'hello',
   'part' => [
        1,
        2,
        3,
        4,
        5,
    ],
}

This is happening because values in Hashes and Arrays have to be SCALAR values. To create the Hash reference correctly to need to store a reference to the @title Array under the key part, you create a reference with a \:

push @books, { subject => "hello", part => \@title };

Note: This also means that when you want to extract the part key into the @temp Array you need to de-reference it (since it is an Array reference):

@temp = @{ $books[$i]{part} };
Comments