tori
tori

Reputation: 33

"Not an ARRAY reference" in Perl

I'm new to Perl and trying to get used to data structures and references in Perl.

I learned

So I combined these two and wrote something like this,

use strict;
use warnings;
use Data::Dumper;

my $hash = {
    key1 => 'value1',
    key2 => 'value2'
};

my $keys = \{ keys %$hash }; # Supposed to be an array reference?

print Dumper $keys; # Output 1
print Dumper $keys->[0]; # Output 2

which yielded the error Not an ARRAY reference at the line of Output 2. Also, Output 1 shows something that looks like a hash reference though it's supposed to be an array reference.

What's wrong with my code?

Similarly, the following code didn't work with the same error.

use strict;
use warnings;

my $array = [1, 2, 3, 4, 5];
my $first_two = \{ @{ $array }[0..1] }; # Isn't it an array ref?
my $first = $first_two->[0];

I guess I misunderstand something about array references.

Upvotes: 3

Views: 1866

Answers (1)

dpkp
dpkp

Reputation: 1459

The problem you have is this is not correct: '\{ @array } returns the reference to the @array' . Instead, the \ is simply prepended to an existing variable, like this: \@array. Braces {} are used to create anonymous hash references, and brackets [] are used to create anonymous array references.

In your example, what you want to do is either (1) store the keys as an array and then use \ to get a reference:

my @keys = keys %$hash;
my $keys = \@keys;

Or (2) use an anonymous array reference:

my $keys = [ keys %$hash ];

Here's a good "reference" ;) https://perldoc.perl.org/perlref.html#Making-References

Upvotes: 6

Related Questions