问题描述
我用 perl 写了这段代码:
I wrote this code in perl:
shift( @interfaces = qx'ifconfig -s' );
并得到这个错误:
Type of arg 1 to shift must be array (not list assignment)
当我这样写时:
@interfaces = qx'ifconfig -s';
shift @interfaces;
它完成了我想要的,即以行数组的形式获取 ifconfig 命令的输出并删除数组中的第一个元素(这是一个标题,而不是实际的接口).
It does what I want, which is to get the output of the ifconfig command as an array of lines and remove the first element in the array (which is a header, not an actual interface).
我个人的偏好是将其写成单行.在我看来,第一个例子中的括号应该导致赋值被完全解析,因此允许 shift 将 @interfaces 视为一个数组,但很明显 perl 认为它是一个列表赋值".
My personal preference is to write this as a one liner. It seems to me the parentheses in the first example should cause the assignment to be resolved fully, therefore allowing shift to see @interfaces as an array, but clearly perl thinks it's a "list assignment."
这对于 perl 大师来说肯定是一个简单的问题,但我已经用谷歌搜索了又谷歌搜索并没有找到启示.
This is surely an easy question for the perl gurus but I've googled and googled and haven't found enlightenment.
如果有人愿意提供特定的语义以在一行中完成我想要的内容,我将不胜感激.如果您也愿意花时间解释为什么我的第一个版本不起作用,我将永远感激(教一个人钓鱼等等).
If someone would please provide the specific semantics to accomplish what I want in one line I would appreciate it. If you would also please take the time to explain why my first version isn't working I would be eternally grateful (teach a man to fish and all that).
预先感谢您的帮助.
推荐答案
如您所见,shift
需要一个文字数组,而不是赋值的结果.这是因为当 perl 解析 shift @interfaces
时,它实际上是将它改写成类似 &CORE::shift(\@interfaces)
的东西,你不能参考一个赋值并获得一个数组引用.
As you saw, shift
requires a literal array, not the result of an assignment. This is because when perl parses shift @interfaces
it is actually rewriting it into something like &CORE::shift(\@interfaces)
and you can not take a reference of an assignment and get an array ref.
您可以将它分成两行,如mob所示,您可以将赋值隐藏在括号内的取消引用中,或者您可以简单地丢弃第一个值:
You could break it into two lines as you have found, you could hide the assignment inside a bracketed dereference as mob shows, or you could simply throw away the first value:
(undef, @interfaces) = qx'ifconfig -s';
undef
在左值位置是不需要的值的占位符.
undef
in an lvalue position is a placeholder for values that you don't need.
(shift
的解析在 perl 5.14+ 中发生了一些变化,但上面的参数仍然成立)
(parsing of shift
has changed a bit in perl 5.14+, but the argument above still holds)
还有一些你可能不应该使用的方法,只能通过增加长度来排序:)
a few more ways that you probably shouldn't use, ordered only by increasing length :)
my @interfaces = sub {shift; @_}->(qx'ifconfig -s');
my @interfaces = sub {@_[1..$#_]}->(qx'ifconfig -s');
my @interfaces = map {@$_[1..$#$_]} [qx'ifconfig -s'];
my @interfaces = map {shift @$_; @$_} [qx'ifconfig -s'];
our @interfaces; shift @{*interfaces = [qx'ifconfig -s']};
my @interfaces = sub {*_ = [qx'ifconfig -s']; shift; @_}->();
这篇关于将列表上下文结果转换为 perl 中一行的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!