如何在Windows的Perl中读取管道输入? [英] How can I read piped input in Perl on Windows?

查看:96
本文介绍了如何在Windows的Perl中读取管道输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Perl中创建类似于Unix tee命令的内容.我正在尝试读取STDIN的每一行,对其进行替换,然后进行打印. (最后,也将其打印到文件中.)如果我使用控制台输入,则此方法有效,但如果尝试将输入传递给命令,则它不会执行任何操作.这是一个简单的示例:

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";

我尝试像这样通过管道将dir命令传递给它:

I try to pipe the dir command to it like this:


C:\perltest>dir | mytee.pl
about to loop
done!

为什么看不到管道输入? (如果相关的话,我在WinXP上使用Perl 5.10.0.)

Why is it not seeing the piped input? (I'm using Perl 5.10.0 on WinXP, if that is relevant.)

推荐答案

这实际上是Windows处理IO重定向的错误.我现在正在寻找参考,但是正是该错误要求您指定

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

而不是能够使用

dir | filter

请参阅Microsoft KB文章从文件关联开始的STDIN/STDOUT重定向可能不起作用:

See Microsoft KB article STDIN/STDOUT Redirection May Not Work If Started from a File Association:

  1. 启动注册表编辑器.
  2. 在注册表中找到然后单击下面的项: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer
  3. 在编辑"菜单上,单击添加值",然后添加以下注册表值:
    • 值名称:InheritConsoleHandles
    • 数据类型:REG_DWORD
    • 基数:Decimal
    • 值数据:1
  1. Start Registry Editor.
  2. Locate and then click the following key in the registry: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer
  3. On the Edit menu, click Add Value, and then add the following registry value:
    • Value name: InheritConsoleHandles
    • Data type: REG_DWORD
    • Radix: Decimal
    • Value data: 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

这篇关于如何在Windows的Perl中读取管道输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆