0

我正在寻找好的形式

if (! write_to_file($data) )
{
    open_this_file($file_name)
    write_to_file($data) or die "Cant write to $file_name" ;
}

它看起来很不清楚,不是吗?如何写它自我解释?

4

4 回答 4

7

or修好就or死!”

假设write_to_file( $data )失败时返回 false:

   write_to_file( $data )
or do { open_this_file( $file_name ); write_to_file( $data ) }
or die "Can't write to $file_name";

do由于运算符优先级,您也可以在没有块的情况下重写它。open_this_file和之间的逗号write_to_file的优先级高于or,所以效果和do块一样:

   write_to_file( $data )
or open_this_file( $file_name ), write_to_file( $data )
or die "Can't write to $file_name";
于 2012-09-26T12:10:02.727 回答
4
for my $try (1..$num_tries) {
    last if write_to_file($data);
    die '...' if $try == $num_tries;
    open_this_file($file_name)
}
于 2012-09-26T12:28:26.640 回答
3
open_this_file($file_name) if not write_to_file($data);
write_to_file($data) or die "Cant write to $file_name";

没有太大区别,但它更清洁,如你所愿..

或者你可以使用这个单线: -

write_to_file($data) or open_this_file($file_name) and 
                        write_to_file($data) or die "Cant write to $file_name";
于 2012-09-26T12:12:20.167 回答
2
sub is_open { return (tell($handle) != -1); }

open_this_file($file_name) if not is_open($handle);
write_to_file($data)       or die "Cant write to $file_name" ;

$handle文件句柄在哪里。

于 2012-09-26T12:11:21.390 回答