Perl 移位运算符简单问题 [英] Perl shift operator simple question
问题描述
下面两行perl的目的是什么??
What's the purpose of the following two lines of perl??
my $host = shift || 'localhost';
my $port = shift || 200;
那应该返回 localhost 和端口 10.什么是 shift 关键字??
That should return localhost and port 10. What is the shift keyword??
推荐答案
这段代码是什么,是一种为 $host
和 $port
提供默认值的方法>.它通常位于脚本或子程序的开头,并分别从 @ARGV
和 @_
获取值.
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.
那应该返回本地主机和端口10.
That should return localhost and port 10.
不,||
运算符是一个短路OR
,这意味着如果LHS 操作数返回真值,则RHS 操作数将被忽略.基本上,这意味着(并且仅此):如果为真,则选择左侧值,否则选择右侧值."
No, the ||
operator is a short circuiting OR
, 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
将返回ARRAY
的第一个值,或者:
shift ARRAY
will return the first value of ARRAY
, or:
如果省略了 ARRAY,则移动 @_词法范围内的数组子程序和格式,以及@ARGV子程序外的数组以及在建立的词法范围内通过 eval STRING , BEGIN {} , INIT{} , 检查 {} , UNITCHECK {} 和 END{} 构造.
If ARRAY is omitted, shifts the @_ array within the lexical scope of subroutines and formats, and the @ARGV array outside a subroutine and also within the lexical scopes established by the eval STRING , BEGIN {} , INIT {} , CHECK {} , UNITCHECK {} and END {} constructs.
引自 http://perldoc.perl.org/functions/shift.html
当然,shift
还会从被移位的数组中移除值.因此,您可以像这样连续使用两个 shift
,以便非常方便地处理参数.
Also, of course, shift
removes the value from the array that is shifted. Therefore you can have two shift
in a row like this, for very convenient argument handling.
这篇关于Perl 移位运算符简单问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!