可选地传递命令行参数?

问题描述:

我需要选择性地接受执行我的脚本的用户的命令行参数。 (我不喜欢使用GetOptions())。可选地传递命令行参数?

我有两个变量,

my ($port_name, $report); 
$port_name = $ARGV[0]; 
$report = $ARGV[1]; 

if (defined $port_name){  
    .... 
} 
if (defined $report){ 
    .... 
} 

如果$report标志不作为命令行参数给出的话,我不想跑第二,如果块。如果没有perl给我一个错误,这怎么能做到呢?

感谢您的帮助。

+1

嗯,你可以不喜欢它,但你还是应该使用[':: Getopt的Long'(HTTP://perldoc.perl .ORG /的Getopt/Long.html)。 – Miller 2014-10-27 18:13:33

+1

__什么错误? – 2014-10-27 18:42:08

您的代码应该按预期工作.....

hi[[email protected] cpanel]# perl blah.pl 1 
hi[[email protected] cpanel]# perl blah.pl 1 2 
hino[[email protected] cpanel]# 

[[email protected] cpanel]# cat blah.pl 
#!/usr/bin/perl 
use strict; 
use warnings; 
my ($port, $report) = @ARGV; 

if ($port) { 
    print 'hi'; 
} 
if ($report) { 
    print 'no'; 
} 
+1

'perl blah.pl 0' – toolic 2014-10-27 18:24:02

+0

他没有询问验证:P – morissette 2014-10-27 18:24:58

+2

这不是验证,而是测试真实性与存在性。 'defined'对此很有帮助。 – Sobrique 2014-10-27 19:58:45