简体   繁体   English

将0作为命令行参数传递的问题

[英]problem passing 0 as command-line argument

I've just noticed a strange behavior of perl5 (5.10.0) when I passed 0 as the command-line argument to a script, which assigns it to a variable. 我刚刚注意到perl5(5.10.0)的奇怪行为,当我将0作为命令行参数传递给脚本时,它将其赋值给变量。 The problem I encountered is that if I give the variable a default value in my script which is greater than 0, say 1, then I can pass any value except 0 to override the default value 1. 我遇到的问题是,如果我在我的脚本中给变量一个大于0的默认值,比如1,那么我可以传递除0之外的任何值来覆盖默认值1。

Following is the code of 'test.pl' I used: 以下是我使用的'test.pl'的代码:

#!/usr/bin/perl -w  
my $x = shift || 1;  
print "x is $x\n";  

Following are the commands and ouputs when I tested it: 以下是我测试时的命令和输出:

$ ./test.pl 2  
x is 2  
$ ./test.pl 0  
x is 1  

I'd appreciate if anyone can shed light on this. 如果有人能说清楚,我会很感激。 Thanks. 谢谢。 wwl WWL

If you want $x to have the value of "1" in case no argument is provided, use this: 如果您希望$x在没有提供参数的情况下具有值“1”,请使用:

my $x = shift // 1;  

From perldoc perlop: 来自perldoc perlop:

"//" is exactly the same as "||", except that it tests the left hand side's definedness instead of its truth. “//”与“||”完全相同,只是它测试左侧的定义而不是它的真实性。

Note: the defined-or operator is available starting from 5.10 (released on December 18th, 2007) 注意:定义的或运算符从5.10开始(2007年12月18日发布)

The expression shift || 1 表达式shift || 1 shift || 1 chooses the rhs iff the lhs evaluates to "false". shift || 1选择rhs iff lhs评估为“false”。 Since you are passing 0, which evaluates to "false", $x ends up with the value 1. 由于您传递0(计算结果为“false”),因此$x最终得到值1。

The best approach is the one in eugene's and Alexandr's answers, but if you're stuck with an older perl, use 最好的方法是在eugene和Alexandr的答案中,但如果你坚持使用旧的perl,请使用

my $x = shift;
$x = 1 unless defined $x;

Because you have a single optional argument, you could examine @ARGV in scalar context to check how many command-line arguments are present. 因为您有一个可选参数,所以可以在标量上下文中检查@ARGV以检查存在多少个命令行参数。 If it's there, use it, or otherwise fall back on the default: 如果它在那里,使用它,或以其他方式回到默认值:

my $x = @ARGV ? shift : 1;

use defined-or operator, because string "0" is defined, but not evaluated as true. 使用defined-或operator,因为字符串“0”已定义,但未评估为true。

#!/usr/bin/perl -w  
my $x = shift // 1;  
print "x is $x\n";  

In this line my $x = shift || 1; 在这一行my $x = shift || 1; my $x = shift || 1; the shift failed the test and therefore the conditional logical OR || 移位未通过测试,因此条件逻辑OR || was executed and assigned 1 to it... as per the page on shift the value was 0 which implies empty array.... 执行并分配给它...根据移位页面的值,该值为0,这意味着空数组....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM