I am trying to create something in Perl that is basically like the Unix tee
command. I'm trying to read each line of STDIN
, run a substitution on it, and print it. (And eventually, also print it to a file.) This works if I'm using console input, but if I try to pipe input to the command it doesn't do anything. Here's a simple example:
print "about to loop\n";
while(<STDIN>)
{
s/2010/2009/;
print;
}
print "done!\n";
I try to pipe the dir command to it like this:
C:\perltest>dir | mytee.pl about to loop done!
Why is it not seeing the piped input? (I'm using Perl 5.10.0 on WinXP, if that is relevant.)
Perl's open function opens a pipe instead of a file when you append or prepend a pipe symbol to the second argument to open. This turns the rest of the arguments into a command, which will be interpreted as a process (or set of processes) that you want to pipe a stream of data either into or out of.
This is actually a bug in how Windows handles IO redirection. I am looking for the reference right now, but it is that bug that requires you to specify
dir | perl filter.pl
rather than being able to use
dir | filter
See Microsoft KB article STDIN/STDOUT Redirection May Not Work If Started from a File Association:
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer
InheritConsoleHandles
REG_DWORD
Decimal
1
C:\Temp> cat filter.pl #!/usr/bin/perl while ( <> ) { print "piped: $_"; }
C:\Temp> dir | filter piped: Volume in drive C is MAIN piped: Volume Serial Number is XXXX-XXXX piped: piped: Directory of C:\Temp> piped: piped: 2010/03/19 03:48 PM . piped: 2010/03/19 03:48 PM .. piped: 2010/03/19 03:33 PM 32 m.pm piped: 2010/03/19 03:48 PM 62 filter.pl
Try:
C:\perltest>dir | perl mytee.pl
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