Wise monks,
I seek your wisdom to enlighten me in this matter:
In short terms:
Why does the close fail, when I try to close the filehandle
before the eof is reached?
my $cmd = '/usr/bin/strings /etc/passwd'; open my $handle, "$cmd |" or die "open: $cmd: $!\n"; # read at least one line while ( <$handle> ) { last; } close $handle or die "$cmd; exit code($?): $!\n";
In longer terms, I tested several external commands and
tested each 100 times:
#!/usr/bin/perl # vi:ts=4 sw=4 et: use strict; use warnings; # these are available commands my %cmd = ( 'cat' => '/bin/cat', 'less' => '/usr/bin/less', 'more' => '/bin/more', 'strings' => '/usr/bin/strings', ); my $textfile = '/etc/passwd'; for my $k ( keys %cmd ) { my $success = 0; for ( 1 .. 100 ) { $success += open_close_pipe( $cmd{$k} ); } print "$cmd{$k}: $success/100 successful!", $/; } sub open_close_pipe { my $ext_cmd = shift; my $cmd = "$ext_cmd $textfile"; open my $handle, "$cmd |" or die "open: $cmd: $!\n"; # read at least one line while ( <$handle> ) { last; } close $handle or do { #warn "exitcode($?): $cmd: $!\n"; # to see exit code ... return 0; }; return 1; } __END__
This was my result:
$ perl read2.pl /bin/cat: 100/100 successful! /usr/bin/less: 38/100 successful! /bin/more: 31/100 successful! /usr/bin/strings: 40/100 successful!
And the results vary (with the same code):
$ perl read2.pl /bin/cat: 100/100 successful! /usr/bin/less: 16/100 successful! /bin/more: 26/100 successful! /usr/bin/strings: 32/100 successful!
When I close the handle directly after opening (comment out the while-loop), the result is like this:
$ perl read2.pl /bin/cat: 35/100 successful! /usr/bin/less: 0/100 successful! /bin/more: 41/100 successful! /usr/bin/strings: 37/100 successful!
When I read from the handle till nothing's left (comment out the last inside the while-loop), it looks fine:
$ perl read2.pl /bin/cat: 100/100 successful! /usr/bin/less: 100/100 successful! /bin/more: 100/100 successful! /usr/bin/strings: 100/100 successful!
Can you please enlighten me and tell me, why the close fails in most cases, when the handle hasn't reached eof?
I tested upon a Linux box with Perl v5.8.8 and Perl v.5.10.0.
edit: "longer terms" included into readmore
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |