Ok, so here’s the entire structure I’m trying to create. I need to create an anonymous array that I can use as a hash value. This works in my program:
$result = {
count, 2,
elementList, [
{name => "John Doe", age => 23},
{name => "Jane Doe", age => 24}
]
};
I’m trying to create the exact same thing with code like this. This works:
my @elements = [
{name => "John Doe", age => 23},
{name => "Jane Doe", age => 24}
];
$result = {
count, 2,
elementList, @elements
};
But this does NOT work:
my @elements;
push(@elements, {name => "John Doe", age => 23});
push(@elements, {name => "Jane Doe", age => 24});
$result = {
count, 2,
elementList, @elements
};
As others have mentioned, you’re describing an unusual data structure: an array with only one element, which is an arrayref of hashrefs. I’ll assume that you really do want that structure for some reason.
is equivalent to
because you want to push the hashrefs onto the arrayref in
$elements[0], not the@elementsarray.But it’s unusual to have an array with only one element. Looking at the additional code you’ve posted, what you really want is this:
Or this:
and then use
\@elementswhere you currently use@elements.Either one of those will work. It’s up to you to decide which one you prefer. I’d probably go with the second version.