加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

如何使用perl命令行参数避免错误并使用strict

发布时间:2020-12-15 21:59:05 所属栏目:大数据 来源:网络整理
导读:添加use strict后,为什么我的代码无效?使用警告;?有没有办法让它发挥作用? 以前,工作代码是: #!/usr/bin/perl -sprint "x: $xn";print "y: $yn"; 我运行的命令是perl -s test.pl -x =“hello”-y =“world”.输出是: x: helloy: world 但是,我添加后
添加use strict后,为什么我的代码无效?使用警告;?有没有办法让它发挥作用?

以前,工作代码是:

#!/usr/bin/perl -s
print "x: $xn";
print "y: $yn";

我运行的命令是perl -s test.pl -x =“hello”-y =“world”.输出是:

x: hello
y: world

但是,我添加后使用严格;使用警告;,我收到以下错误:

Variable "$x" is not imported at test.pl line 4.
Variable "$y" is not imported at test.pl line 5.
Global symbol "$x" requires explicit package name at test.pl line 4.
Global symbol "$y" requires explicit package name at test.pl line 5.
Execution of test.pl aborted due to compilation errors.

我知道我需要声明我的$x和我的$y来修复第3和第4个错误.但前两个错误意味着什么,我该如何克服它?

解决方法

您正在使用一个基本的开关解析器perl -s,它使用全局变量.为了使它与use strict一起使用,你需要引用全局变量:$main :: x,如ruakh指出的那样.

但即便如此,词汇变量(用我的声明)在几乎所有情况下都是可取的.做就是了:

use strict;
use warnings;

my ($x,$y) = @ARGV;
print "x: $xn";
print "y: $yn";

并使用:

perl test.pl hello world

有关更详细和类似开关的处理,请查看Getopt::Long模块.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读