我很难理解,为什么 Perl 在这样的程序中执行花括号中的代码:
unknown_method {
# some code
};
我的程序:
文件交易.pm:
package Transaction;
use strict;
use warnings;
use feature qw/ say /;
sub transaction(&) {
say 'BEGIN TRANSACTION';
eval {
shift->()
};
if ( $@ ) {
say 'ROLLBACK TRANSACTION';
die($@); # reraise error
} else {
say 'COMMIT TRANSACTION';
}
}
1;
文件 run_properly.pl:
use feature qw/ say /;
use Transaction;
eval {
Transaction::transaction {
say "insert some data to DB";
die("KnownException")
}
};
warn $@;
文件 run_wrong.pl:
use feature qw/ say /;
# I forgot to import Transaction
eval {
Transaction::transaction {
say "insert some data to DB";
die("KnownException")
}
};
warn $@;
执行:
$ perl run_properly.pl
BEGIN TRANSACTION
insert some data to DB
ROLLBACK TRANSACTION
KnownException at run_properly.pl line 6.
和
$ perl run_wrong.pl
insert some data to DB
KnownException at run_wrong.pl line 6.
为什么 Perl 允许这样的事情?