为什么我添加后我的代码无效use strict; use warnings;?有没有办法让它发挥作用?
以前,工作代码是:
#!/usr/bin/perl -s
print "x: $x\n";
print "y: $y\n";
Run Code Online (Sandbox Code Playgroud)
我跑的命令是perl -s test.pl -x="hello" -y="world".输出是:
x: hello
y: world
Run Code Online (Sandbox Code Playgroud)
但是,在我添加之后use strict; use warnings;,我收到以下错误:
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.
Run Code Online (Sandbox Code Playgroud)
我知道我需要声明my $x并my $y修复第3和第4个错误.但前两个错误意味着什么,我该如何克服它?
实际上,将这些变量声明为lexical(my)变量将无济于事,因为它太"迟"了:-s交换机已经设置了它们.它设置全局(包)变量(在您的情况下,$main::x和$main::y- 或 - 作为一种特殊的简写 - $::x和$::y).如果您不想使用其包限定名称来引用它们,那么您可以使用our声明来指示裸名称$x并$y引用当前包中的$x和$y:
our ($x, $y);
print "x: $x\n";
print "y: $y\n";
Run Code Online (Sandbox Code Playgroud)
(帽子提示derobert指出你可以用our它.)
或者,您可以将全局变量复制到具有相同名称的词法变量中:
my ($x, $y) = ($::x, $::y);
print "x: $x\n";
print "y: $y\n";
Run Code Online (Sandbox Code Playgroud)
这将处理两组诊断.
您正在使用一个基本的 switch parser perl -s,它使用全局变量。为了让它工作,use strict你需要参考全局变量:$main::x正如鲁阿赫指出的那样。
但即便如此,词法变量(用 声明my)在几乎所有情况下都是更可取的。做就是了:
use strict;
use warnings;
my ($x, $y) = @ARGV;
print "x: $x\n";
print "y: $y\n";
Run Code Online (Sandbox Code Playgroud)
并与以下一起使用:
perl test.pl hello world
Run Code Online (Sandbox Code Playgroud)
有关更详细的类似开关的处理,请查看Getopt::Long模块。
| 归档时间: |
|
| 查看次数: |
6400 次 |
| 最近记录: |