Reputation: 15844
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
};
Upvotes: 0
Views: 676
Reputation: 62109
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.
my @elements = [
{name => "John Doe", age => 23},
{name => "Jane Doe", age => 24}
];
is equivalent to
my @elements = [];
push(@{ $elements[0] }, {name => "John Doe", age => 23});
push(@{ $elements[0] }, {name => "Jane Doe", age => 24});
because you want to push the hashrefs onto the arrayref in $elements[0]
, not the @elements
array.
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:
my $elementsRef = [];
push(@$elementsRef, {name => "John Doe", age => 23});
push(@$elementsRef, {name => "Jane Doe", age => 24});
Or this:
my @elements;
push(@elements, {name => "John Doe", age => 23});
push(@elements, {name => "Jane Doe", age => 24});
and then use \@elements
where 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.
Upvotes: 7
Reputation: 6524
[] makes a reference to an empty array. You are creating an array with one element. Just say:my @elements;
to make an empty array.
Upvotes: 3
Reputation: 47072
Wrong brackets.
You actually need to build a structure like this:
my @elements = (
{name => "John Doe", age => 23},
{name => "Jane Doe", age => 24}
);
To do it in a loop, you will need to modify this code:
my @elements; # same as my @elements = ();
push(@elements, {name => "John Doe", age => 23});
push(@elements, {name => "Jane Doe", age => 24});
The reason is that the square brackets build a reference to an array. A reference to an array is not the same thing as an array.
To make a list of elements to assign to an array, use round brackets ()
.
Upvotes: 3
Reputation: 42154
You are assigning an array reference (the []
syntax) to your array. As a first and only element since you don't specify any others.
You wanted to directly assign a list there, using parentheses ()
instead of the square brackets.
Check out perldsc
for an introduction on the subject.
Upvotes: 5