Understanding Perl's `eval` -
i trying understand perl's eval
function. here test script wrote:
[red@tools-dev1 ~]$ cat evaltest.pl #!/usr/local/bin/perl -w use strict; while(<data>) { chomp; ($arg1, $arg2, $op ) = split /,/; $cmd = "$arg1 $op $arg2"; print "$cmd\n"; $rc = eval { $cmd }; print "rc [$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,<=
when execute output ...
[red@tools-dev1 ~]$ ./evaltest.pl 1 != 2 rc [1 != 2] 1 != 1 rc [1 != 1] 1 = 2 rc [1 = 2] 1 = 1 rc [1 = 1] 1 == 2 rc [1 == 2] 2 > 3 rc [2 > 3] 3 > 2 rc [3 > 2] 3 > 3 rc [3 > 3] 2 >= 3 rc [2 >= 3] 3 >= 2 rc [3 >= 2] 3 >= 3 rc [3 >= 3] 2 < 3 rc [2 < 3] 3 < 2 rc [3 < 2] 3 < 3 rc [3 < 3] 2 <= 3 rc [2 <= 3] 3 <= 2 rc [3 <= 2] 3 <= 3 rc [3 <= 3]
... trying output looks more this:
1 != 2 rc [1] 1 != 1 rc [0] 1 = 2 rc [0] 1 = 1 rc [1] 1 == 2 rc [0] 2 > 3 rc [0] 3 > 2 rc [1] 3 > 3 rc [0] 2 >= 3 rc [0] 3 >= 2 rc [1] 3 >= 3 rc [1] 2 < 3 rc [1] 3 < 2 rc [0] 3 < 3 rc [0] 2 <= 3 rc [1] 3 <= 2 rc [0] 3 <= 3 rc [1]
there 2 forms of eval, , confusing them. 1 (eval block
) compiles block when eval compiled; thing catch exceptions , store them in $@
. looking eval string
, compiles , executes perl code in given expression (storing compile time errors or run time exceptions in $@
).
so eval $cmd
instead of eval { $cmd }
.
also note comparison operators return special boolean false value empty string in string context 0 in numeric context, output have rc []
, not rc [0]
.
when there compile error (which happen 1 = 1
, 1 = 2
), eval return undef (and mentioned, place error in $@
).
Comments
Post a Comment