Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Not an ARRAY reference" in Perl

Tags:

perl

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

I learned

  • key %hash returns an array of the keys in %hash
  • \{ @array } returns the reference to the @array

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.

like image 478
tori Avatar asked Apr 05 '26 22:04

tori


1 Answers

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

like image 87
dpkp Avatar answered Apr 08 '26 14:04

dpkp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!