1

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"
    }
}
2

1 Answer 1

4

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} };
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.