Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl using `IO::Handle` or `IO::File` when not reading actual files

Tags:

file-io

perl

I like using IO::File to open and read files rather than the built in way.

Built In Way

 open my $fh, "<", $flle or die;

IO::File

 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 image 311
David W. Avatar asked Nov 01 '25 19:11

David W.


1 Answers

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.
like image 60
ikegami Avatar answered Nov 04 '25 02:11

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!