Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: How do I declare empty array refs in a new hash?

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?)

like image 969
VolatileRig Avatar asked Dec 22 '11 03:12

VolatileRig


People also ask

How do I declare an empty hash in Perl?

This command will declare an empty hash: my %hash; Similar to the syntax for arrays, hashes can also be declared using a list of comma separated values: my %weekly_temperature = ('monday', 65, 'tuesday', 68, 'wednesday', 71, 'thursday', 53, 'friday', 60);

How do I create a hash reference in Perl?

Similar to the array, Perl hash can also be referenced by placing the '\' character in front of the hash. The general form of referencing a hash is shown below. %author = ( 'name' => "Harsha", 'designation' => "Manager" ); $hash_ref = \%author; This can be de-referenced to access the values as shown below.


2 Answers

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]

like image 55
Eric Strom Avatar answered Sep 17 '22 15:09

Eric Strom


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.

like image 24
TLP Avatar answered Sep 18 '22 15:09

TLP