理解Perl的'eval`

时间:2015-06-02 16:50:07

标签: perl

我正在尝试了解Perl的[red@tools-dev1 ~]$ cat evaltest.pl #!/usr/local/bin/perl -w use strict; while(<DATA>) { chomp; my ($arg1, $arg2, $op ) = split /,/; my $cmd = "$arg1 $op $arg2"; print "$cmd\n"; my $rc = eval { $cmd }; print "rc is [$rc]\n"; } __DATA__ 1,2,!= 1,1,!= 1,2,= 1,1,= 1,2,== 2,3,> 3,2,> 3,3,> 2,3,>= 3,2,>= 3,3,>= 2,3,< 3,2,< 3,3,< 2,3,<= 3,2,<= 3,3,<= 函数。 这是我写的测试脚本:

[red@tools-dev1 ~]$ ./evaltest.pl 
1 != 2
rc is [1 != 2]
1 != 1
rc is [1 != 1]
1 = 2
rc is [1 = 2]
1 = 1
rc is [1 = 1]
1 == 2
rc is [1 == 2]
2 > 3
rc is [2 > 3]
3 > 2
rc is [3 > 2]
3 > 3
rc is [3 > 3]
2 >= 3
rc is [2 >= 3]
3 >= 2
rc is [3 >= 2]
3 >= 3
rc is [3 >= 3]
2 < 3
rc is [2 < 3]
3 < 2
rc is [3 < 2]
3 < 3
rc is [3 < 3]
2 <= 3
rc is [2 <= 3]
3 <= 2
rc is [3 <= 2]
3 <= 3
rc is [3 <= 3]

当我执行时,我得到这个输出......

1 != 2
rc is [1]
1 != 1
rc is [0]
1 = 2
rc is [0]
1 = 1
rc is [1]
1 == 2
rc is [0]
2 > 3
rc is [0]
3 > 2
rc is [1]
3 > 3
rc is [0]
2 >= 3
rc is [0]
3 >= 2
rc is [1]
3 >= 3
rc is [1]
2 < 3
rc is [1]
3 < 2
rc is [0]
3 < 3
rc is [0]
2 <= 3
rc is [1]
3 <= 2
rc is [0]
3 <= 3
rc is [1]

...我试图获得看起来更像这样的输出:

- (void)addVideoTrackWithSourceFormatDescription:(CMFormatDescriptionRef)formatDescription transform:(CGAffineTransform)transform settings:(NSDictionary *)videoSettings

1 个答案:

答案 0 :(得分:6)

有两种形式的评估,你会混淆它们。一个(eval BLOCK)在编译eval本身时编译BLOCK;它唯一能做的就是捕获异常并将它们存储在$@中。您正在寻找eval STRING,它编译并执行给定表达式中的Perl代码(在$@中存储任何编译时错误或运行时异常)。

所以只说eval $cmd而不是eval { $cmd }

另请注意,比较运算符返回一个特殊的布尔值false值,该值在字符串上下文中为空字符串,但在数字上下文中为0,因此您的输出将为rc is [],而不是rc is [0]

如果存在编译错误(将发生1 = 11 = 2),eval将返回undef(正如我所提到的,将错误放在$@中)。< / p>