Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl, dereference array of references

In the following Perl code, I would expect to be referencing an array reference inside an array

#!/usr/bin/perl

use strict;
use warnings;

my @a=([1,2],[3,4]);

my @b = @$a[0];

print $b[0];

However it doesn't seem to work. I would expect it to output 1.

@a is an array of references

@b is $a[1] dereferenced (I think)

So what's the problem?

like image 338
Mike Avatar asked Jun 03 '10 20:06

Mike


People also ask

How do I create an anonymous array in Perl?

Perl anonymous references These types of references are called anonymous references. The rules of creating anonymous references are as follows: To get an array reference, use square brackets [] instead of parentheses. To get a hash reference, use curly brackets {} instead of parentheses.

How do I check if an array is empty in Perl?

A simple way to check if an array is null or defined is to examine it in a scalar context to obtain the number of elements in the array. If the array is empty, it will return 0, which Perl will also evaluate as boolean false.


1 Answers

This stuff is tricky.

@$a[0] is parsed as (@$a)[0], dereferencing the (undefined) scalar $a

You wanted to say @{$a[0]}.

like image 174
mob Avatar answered Oct 19 '22 12:10

mob