Perl pipe open example and how to handle command line arguments with space 

Joined:
04/09/2007
Posts:
753

December 05, 2009 20:12:16    Last update: December 05, 2009 20:46:45
It's quite easy for Perl to open a pipe and read from it:
$file = "nospace.txt";
open(IN, "cat $file |") or die "Can't open pipe: $!";
while (<IN>) { # read line into default varieble $_
    print; # print defaut variable $_
}
close IN;


But the code breaks when the file name contains a space:
# This does not work!
$file = "yes space.txt";
open(IN, "cat $file |") or die "Can't open pipe: $!";
while (<IN>) { # read line into default varieble $_
    print; # print defaut variable $_
}
close IN;


On Windows, these don't work either:
# This does not work!
$file = "yes space.txt";
open(IN, "cat \"$file\" |") or die "Can't open pipe: $!";
open(IN, "cat '$file' |") or die "Can't open pipe: $!";


You need to use a technique called Safe Pipe Opens:
$file = "yes space.txt";
$prog = "cat";

$pid = open(IN, "-|"); # open pipe to read from child
$SIG{PIPE} = sub { die "whoops, $prog pipe broken" };
if ($pid) { # praent
    while (<IN>) { # read line into default varieble $_
	print; # print defaut variable $_
    }
    close IN or warn "Child exit code: $?";
}
else { # child
    exec("cat", $file) or die "Can't exec $prog: $!";
}



Share |
| Comment  | Tags