I like using IO::File to open and read files rather than the built in way. 
 open my $fh, "<", $flle or die;
 use IO::File;
 my $fh = IO::File->new( $file, "r" );
However, what if I am treating the output of a command as my file?
The built in open function allows me to do this:
open my $cmd_fh, "-|", "zcat $file.gz" or die;
while ( my $line < $cmd_fh > ) {
    chomp $line;
}
What would be the equivalent of IO::File or IO::Handle?
By the way, I know can do this:
open my $cmd_fh,  "-|", "zcat $file.gz" or die;
my $cmd_obj = IO::File-> new_from_fd( fileno( $cmd_fh ), 'r' );
But then why bother with IO::File if there's already a file handle?
Like this:
use String::ShellQuote qw( shell_quote );
my $cmd_fh = IO::File->open( shell_quote( "zcat", "$file.gz" ) . "|" )
   or die $!;
First of all, your snippet fails if $file contains spaces or other special characters.
open( my $cmd_fh,  "-|", "zcat $file.gz" )
   or die $!;
should be
open( my $cmd_fh,  "-|", "zcat", "$file.gz" )
   or die $!;
or
use String::ShellQuote qw( shell_quote );
open( my $cmd_fh,  "-|", shell_quote( "zcat", "$file.gz" ) )
   or die $!;
or
use String::ShellQuote qw( shell_quote );
open( my $cmd_fh,  shell_quote( "zcat", "$file.gz" ) . "|" )
   or die $!;
I mention the latter variants because passing a single arg to IO::File->open boils down to passing that arg to open( $fh, $that_arg ), so you could use
use String::ShellQuote qw( shell_quote );
my $cmd_fh = IO::File->open( shell_quote( "zcat", "$file.gz" ) . "|" )
   or die $!;
If all you want is to use IO::File's methods, you don't need to use IO::File->open.
use IO::Handle qw( );  # Needed on older versions of Perl
open my $cmd_fh,  "-|", "zcat", "$file.gz" or die $!;
$cmd_fh->autoflush(1);  # Example.
$cmd_fh->print("foo");  # Example.
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With