我编写了简单的代码片段,用于处理在受限制的(我们需要root权限的情况下)打开文件时发生的错误 以下代码工作正常并且出现错误作为O/p在perl中打开文件时使用try/catch或eval进行错误处理
#!/usr/bin/perl
use strict;
use warnings;
use Try::Tiny;
my $file_name = "/var/log/test.txt"; # needs root permission to create file
if(open(HAN, ">$file_name")){
print "sucuessfully opened file \n ";
} else {
print "Error with if/else while openning file : $! \n";
}
O/p:
误差的if/else在打开文件:权限被拒绝
当我使用try/catch语句或EVAL具有相同的代码,并打开文件
try {
open(HAN, ">$file_name");
} catch {
print "Error with try/catch while opening file : $_ \n";
};
或
eval {
open(HAN, ">$file_name");
};
print " Error with eval while opening file : [email protected] \n";
它显示在$无输出_或$ @,这是为什么happing?
总是把'使用警告' – 2013-03-01 13:01:43
通常使用的语法是使用open()或死“$!”; – run 2013-03-01 13:06:21
@ run-thanks,我知道我们可以使用“$!”对于open(),但试图探索用try..catch或eval来做到这一点。 – Ganesh 2013-03-01 13:50:57