Perl移位运算符简单问题
下面两行perl的目的是什么?
my $host = shift || 'localhost';
my $port = shift || 200;
这应该返回 localhost 和端口 10。shift 关键字是什么?
What's the purpose of the following two lines of perl??
my $host = shift || 'localhost';
my $port = shift || 200;
That should return localhost and port 10. What is the shift keyword??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
第一行从
@_
或@ARGV
转移(取决于您在代码中的位置),或者在@_< 中没有任何内容的情况下/code>/
@ARGV
,将localhost
分配给$host
。第二个现在应该是不言自明的。
有关详细信息,请参阅轮班文档。
The first line shifts from either
@_
or@ARGV
(depending on where you are in the code), or in the absence of any contents in@_
/@ARGV
, assignslocalhost
to$host
.The second one should be self-explanatory now.
Have a look at the shift documentation for details.
这段代码是为
$host
和$port
提供默认值的一种方法。它通常位于脚本或子例程的开头,并分别从@ARGV
和@_
获取值。不,
||
运算符是短路OR
,这意味着如果左操作数返回真值,则忽略右操作数。基本上,它的意思是(并且仅此):“如果为真,则选择左侧值,否则选择右侧值。”shift ARRAY
将返回ARRAY
的第一个值,或者:引自 http://perldoc.perl.org/functions/shift.html
另外,当然,
shift
会从移动的数组中删除值。因此,您可以像这样连续放置两个shift
,以便非常方便地处理参数。What this piece of code is, is a way to provide default values for
$host
and$port
. It will typically be at the start of a script or a subroutine, and take values from@ARGV
and@_
respectively.No, the
||
operator is a short circuitingOR
, which means that if the LHS operand returns a true value, the RHS operand is ignored. Basically, it means this (and ONLY this): "choose the left hand side value if it is true, otherwise choose the right hand side value."shift ARRAY
will return the first value ofARRAY
, or:Quoted from http://perldoc.perl.org/functions/shift.html
Also, of course,
shift
removes the value from the array that is shifted. Therefore you can have twoshift
in a row like this, for very convenient argument handling.如果没有提供参数,shift 会将 @ARGV 移到子例程之外,将 @_ 移到子例程内子例程——即传递给主程序或子例程的参数数组。
在您的情况下,$host 被分配@ARGV(或@_,如果代码位于子内部)或“localhost”的第一个元素(如果该元素为 false)。
这是一个非常常见的 Perl 习惯用法。
If no argument is provided, shift will shift @ARGV outside a subroutine and @_ inside a subroutine – that is the argument array passed to either the main program or the subroutine.
In your case, $host is assigned the first element of @ARGV (or @_, if the code is inside a sub) or 'localhost', if the element is false.
This is a very common Perl idiom.
shift 返回数组的第一个元素并将其从数组中删除。就像流行音乐一样,但来自另一端。
shift return the first element of an array and removes it from the array. Like pop, but from the other end.
如果您使用
shift
,请始终将数组放在上面。我见过经验丰富的 Perl 程序员忘记了在子例程之外,shift
可以在@ARGV
上工作。程序员必须同时记住的东西越多,他犯错误的可能性就越大。If you use
shift
, always put the array on it. I've seen experience Perl programmers forget that outside a subroutine,shift
works on@ARGV
. The more things a programmer has to remember at the same time, the more likely he is to make an error.