在一个语句中取消引用数组中的数组?

Dereference array within an array in one statement?

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

是否可以在一条语句中执行第 2 行和第 3 行?

我已经试过@arr2 = @$arr1[0];但它没有编译。

由于优先规则,您必须添加大括号

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

来自 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!


这意味着如果不需要显式索引,那么就不需要 {},例如在已经检索数组元素的代码中。例如,根据 Sobrique 的评论

,将一个包含数组引用的数组展平
@all_elems = map { ref $_ eq "ARRAY" ? @$_ : $_ } @arr1;

要仅检索 arrayrefs 的内容,可以在块内的三元运算符中使用 : () 而不是 : $_() returns 一个空列表,它在结果中变平,因此不会影响它。 (当条件评估为假时 必须返回某些东西 。这个技巧允许 map 完成 grep 的工作,有效地过滤。)