<?xml version="1.0" encoding="windows-1252"?>
<node id="979163" title="close and autodie on pipes" created="2012-06-29 14:06:27" updated="2012-06-29 14:06:27">
<type id="115">
perlquestion</type>
<author id="716717">
apomatix</author>
<data>
<field name="doctext">
&lt;p&gt;I want to get both the output and status of a pipe.
Here is a working example:&lt;/p&gt;

&lt;code&gt;
#!/usr/bin/perl
use strict;

open my $fh, '-|', 'bash -c "echo Hello; exit 1"';
print &lt;$fh&gt;;
close $fh;
my $status = $? &gt;&gt; 8;
print "$status\n";
&lt;/code&gt;

&lt;p&gt;Fine. It outputs&lt;/p&gt;

&lt;code&gt;
Hello
1
&lt;/code&gt;

&lt;p&gt;Now let's try to use autodie:&lt;/p&gt;

&lt;code&gt;
#!/usr/bin/perl
use strict;
use autodie;

open my $fh, '-|', 'bash -c "echo Hello; exit 1"';
print &lt;$fh&gt;;
close $fh;
my $status = $? &gt;&gt; 8;
print "$status\n";
&lt;/code&gt;

&lt;p&gt;No good, that breaks it:&lt;/p&gt;

&lt;code&gt;
Hello
Can't close(GLOB(0x10082a098)) filehandle: '' at test.pl line 7
&lt;/code&gt;

&lt;p&gt;It is the "close" statement. So we can take that out.&lt;/p&gt;

&lt;code&gt;
use strict;
use autodie;

open my $fh, '-|', 'bash -c "echo Hello; exit 1"';
print &lt;$fh&gt;;
#close $fh;
my $status = $? &gt;&gt; 8;
print "$status\n";
&lt;/code&gt;

&lt;p&gt;Now it is broken differently---it has lost the exit status:&lt;/p&gt;

&lt;code&gt;
Hello
0
&lt;/code&gt;

&lt;p&gt;I need to call close in order to get the exit status of a pipe.&lt;/p&gt;

&lt;p&gt;So now I have settled on this ugly thing:&lt;/p&gt;

&lt;code&gt;
use strict;
use autodie;

open my $fh, '-|', 'bash -c "echo Hello; exit 1"';
print &lt;$fh&gt;;
{no autodie;
 close $fh;}
my $status = $? &gt;&gt; 8;
print "$status\n";
&lt;/code&gt;

&lt;p&gt;That seems to work, but I'm not doing any error checking on the close statement:&lt;/p&gt;

&lt;code&gt;
Hello
1
&lt;/code&gt;

Can I use close with autodie when my pipe fails? If not, how should I check for errors?</field>
</data>
</node>
