Kevin
Kevin

Reputation: 779

Accessing Arrays in Perl hashes

I have an array in a perl hash declared like this:

my %updatevars = (datapoints => []);

I'm later trying to add elements to it like this:

push($updatevars{'datapoints'}, [$updatestart+$i, $bandwidth]);

I get this error:

Type of arg 1 to push must be array (not hash element) at dirlist.pl line 61, near "])"

Upvotes: 0

Views: 115

Answers (3)

ikegami
ikegami

Reputation: 386696

Hashes (and arrays) can only contain scalars. That's why we must put reference to arrays (and hashes) in them. $updatevars{datapoints} contains a reference to an array. As such, you need to use

push @{ $updatevars{datapoints} }, [ $updatestart+$i, $bandwidth ];

Note that your code would work on 5.14+ as push was changed to also accept a reference. (This change is "considered highly experimental" however, so you should use the above code in newer versions too.)

Upvotes: 6

TLP
TLP

Reputation: 67920

$updatevars{'datapoints'} is an array ref, as you assigned it: []. push takes an array as argument, not an array reference. So you need to dereference your reference:

push @{ $updatevars{'datapoints'} }, ...

In Perl v5.14, you may use a reference, as noted in the documentation. But it does not sound like it is a recommended practice just yet.

Starting with Perl 5.14, "push" can take a scalar EXPR, which must hold a reference to an unblessed array. The argument will be dereferenced automatically. This aspect of "push" is considered highly experimental. The exact behaviour may change in a future version of Perl.

Upvotes: 3

psxls
psxls

Reputation: 6935

Try this:

push @{$updatevars{'datapoints'}}, [$updatestart+$i, $bandwidth];

Since push takes an array and $updatevars{'datapoints'} is an array reference, you have to de-reference it by putting the @{} in front.

Upvotes: 2

Related Questions