CJ7
CJ7

Reputation: 23275

Dereference array within an array in one statement?

@arr1 = ([1,2,3], 4, 5, 6);
$arr_ref = $arr1[0];
@arr2 = @$arr_ref;

Is it possible to do lines 2 and 3 in one statement?

I have tried @arr2 = @$arr1[0]; but it doesn't compile.

Upvotes: 0

Views: 95

Answers (1)

zdim
zdim

Reputation: 66873

You have to add the braces because of the precedence rules

@arr2 = @{$arr1[0]};

From perldsc, Caveat on precedence

Speaking of things like @{$AoA[$i]}
[ ... ]
That's because Perl's precedence rules on its five prefix dereferencers (which look like someone swearing: $ @ * % & ) make them bind more tightly than the postfix subscripting brackets or braces!


This implies that if explicit indexing isn't needed then there is no need for {}, for instance in code that retrieves array elements already. For example, to flatten an array with arrayrefs inside, per Sobrique's comment

@all_elems = map { ref $_ eq "ARRAY" ? @$_ : $_ } @arr1;

To retrieve content of only arrayrefs one can use : () instead of : $_ in the ternary operator inside the block. The () returns an empty list that gets flattened in the result thus not affecting it. (When the condition evaluates to false something has to be returned. This trick allows map to do grep's work, effectively filtering.)

Upvotes: 5

Related Questions