Perl: How do I declare empty array refs in a new hash?
Solution 1
Elements of a hash can only be scalars, so you have to change your assignment to use the anonymous array constructor instead of parens:
$hash{$key} = [$row, [], [], [], ''];
See perldsc for more information.
The line:
$hash{$key}->[4] = $hash{$key}->[4] . 'More Data';
could be written:
$hash{$key}->[4] .= 'More Data';
And finally, unless you like them, the ->
characters are implicit between subscript delimiters, so $hash{$key}->[1]->[3]
means the same thing as $hash{$key}[1][3]
Solution 2
I'm not quite sure what you are trying to do, but if you want to assign an array to a scalar value, you need to use brackets to create an anonymous array:
$hash{$key} = [$row, [], [], [], ''];
In your case, what you are attempting to do is interpreted as follows:
$row, [], [], [];
$hash{$key} = '';
Because you cannot assign a list of values to a scalar (single value variable). You can, like we did above, however, assign a reference to an anonymous array containing a list of values to a scalar.
Solution 3
You almost got it.
Remember that every hash and array value must be a scalar, so if you want a hash of arrays, you have to assign an array reference to your hash key. So:
$hash{$key} = [ $row, [], [], [], '' ];
is what you want.
VolatileRig
Currently Innovating at Hiya Inc. Super Important Legalese: I don't represent or speak on behalf of my employer or any of its subsidiaries, partners or affiliates. Anything posted here or on other sites by me are my own views/opinions, no one else's. Any code I write here or on other sites comes with no implicit or explicit guarantees, promises, license, or warranty and I'm not liable for any damages as a result of running that code (please inspect and use discretion when running ANYONE's code).
Updated on June 04, 2022Comments
-
VolatileRig almost 2 years
I've got strict and warnings on, but it keeps complaining about the initialization of the following line:
$hash{$key} = ($row, [], [], [], '');
It warns for that single line:
"Useless use of private variable in void context" "Useless use of anonymous list ([]) in void context" (3 times)
I am filling the data in later, but I want indexes 1, 2, 3 to be array references, and index 4 to be a string. I am accessing and filling the data like so:
$hash{$key}->[1]->[3] = 'Data'; $hash{$key}->[4] = $hash{$key}->[4] . 'More Data';
Obviously, I'm doing something wrong, but I'm not exactly sure how to make it right. (Also, I'm aware that that last line is redundant, could that also be summed up in a nicer way?)