1

我知道我可以使用 require 并以不同的方式执行此操作,但我只是在玩弄 perl 并遇到了一些我不知道如何解释的东西。

这是我的第一个脚本:

use 5.16.2;
use warnings;

sub get
{
print "hello";
}

get();

测试脚本:

use 5.16.2;
use warnings;

my $val=system('perl test.pl');
print "$val\n";

#prints: hello0, I surmised that 0 is the return code for system

我查找了如何忽略 0 并得到了一些错误的东西,但导致我这样做:

print '', system('perl test.pl');

#also prints hello0

my $val='', system('perl test.pl');
print "$val\n";
#prints: hello

这行得通,但我完全不知道为什么。我也很困惑为什么前面的那个不起作用。有人可以解释一下吗?

4

1 回答 1

3

这:

print '', system('perl test.pl');

使用两个参数调用print,即''(空字符串:无效)和system('perl test.pl')0如您所见,如果perl test.pl运行成功,则计算结果为 )。

使用更多的括号更明确,您可以将上面的内容写为:

print('', system('perl test.pl'));

或者你可以把它写成:

my $val = system 'perl test.pl'; # prints 'hello', sets $val to zero
print '', $val; # prints zero

这:

my $val='', system('perl test.pl');

声明$val为局部变量并将其设置为''(空字符串),并且(不相关地)调用system('perl test.pl'). 使用括号表示明确:

(my $val = ''), system('perl test.pl');

或者:

my $val = '';
system('perl test.pl'); # prints 'hello', discards exit-status
于 2013-05-14T05:17:45.920 回答