note
haukex
<blockquote><i>I think there's no <MYPIPE> if open fails</i></blockquote>
<p>Yes and no: the first <c><MYPIPE></c> does return <c>undef</c>, so the <c>while</c> loop never runs, but you should also be getting a warning "<c>readline() on closed filehandle</c>", indicating that something is wrong. A failed [doc://open] doesn't <i>have</i> to be fatal, there are plenty of ways to handle the control flow:</p>
<c>
if ( open my $fh, ... ) {
while (<$fh>) { ... }
close $fh;
}
else { warn "open: $!" }
# - or -
sub foo {
open my $fh, ... or do { warn "open: $!"; return };
while (<$fh>) { ... }
close $fh;
}
# - or -
FILE: for my $file (@files) {
open my $fh, ...
or do { warn "skipping $file: $!"; next FILE };
while (<$fh>) { ... }
close $fh;
}
# - or -
use Try::Tiny;
try {
open my $fh, ... or die $!;
while (<$fh>) { ... }
close $fh;
}
catch {
warn "error: $_";
};
# same thing, but without the module:
eval {
open my $fh, ... or die $!;
...
;1 } or do {
warn "error: $@";
};
</c>
<p>The fourth and fifth examples are different in that they catch any fatal error inside the block, which may or may not be desired.</p>
<p><b>Update:</b> Added the third example, from [id://11101758|this thread].</p>
11101695
11101699