我的 perl 程序遇到这个问题,该程序正在从文件中读取(我在 STDIN 上打开该文件并使用 $line = <>
一次读取每一行)。执行“反引号”命令后,然后从 STDIN 读取下一行,我得到一个 undef,表示 EOF。我使用调试代码将其与反引号命令隔离,如下所示:
my $dir = dirname(__FILE__);
say STDERR "before: tell(STDIN)=" . tell(STDIN) . ", eof(STDIN)=" . eof(STDIN);
say STDERR "\@export_info = `echo nostdin | perl $dir/pythonizer_importer.pl $fullfile`;";
@export_info = `echo nostdin | perl $dir/pythonizer_importer.pl $fullfile`;
say STDERR "after: tell(STDIN)=" . tell(STDIN) . ", eof(STDIN)=" . eof(STDIN);
输出为:
before: tell(STDIN)=15146, eof(STDIN)=
@export_info = `echo nostdin | perl ../pythonizer_importer.pl ./Pscan.pm`;
after: tell(STDIN)=15146, eof(STDIN)=1
我最近添加了 echo nostdin |
到 perl 命令没有效果。如何运行此命令并获取 STDOUT 而不会弄乱我的 STDIN?顺便说一句,这一切都在 Windows 上运行。如果重要的话,我会从 git bash 中关闭主程序。
最佳答案
在运行反引号命令之前尝试在本地取消定义 STDIN,就像此示例脚本一样。请注意,从调用 local 的 sub 调用的任何子例程都将看到新值。您还可以open STDIN, "<", "file for child process to read";
local *STDIN
之后但在反引号之前但记得close()
将 STDIN 恢复为其旧值之前的文件。
子进程正在影响您的 STDIN,因为“该命令使用的 STDIN 文件句柄是从 Perl 的 STDIN 继承的。” –perlop manual
这只是一个例子;在您的实际脚本中,将 sed 命令替换为您要运行的实际命令。
use strict;
use warnings;
#Run a command and get its output
sub get_output {
# Prevent passing our STDIN to child process
local *STDIN = undef;
print "Running sed\n";
#replace the sed command with the actual command you want to run
return `sed 's/a/b/'`;
}
my $output = get_output();
print $output;
#We can still read STDIN even after running a child process
print "Waiting for input\n";
print "Readline is " . scalar readline;
输入:
a
b
c
^D
line
输出:
Running sed
b
b
c
Waiting for input
Readline is line
关于Perl 反引号子进程导致 STDIN 上出现 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71504096/