问题描述
我基本上想这样做:
$_ = "some content that need to be escaped &>|\"$\'`\s\\";
qx{echo $_ | foo}
这里有两个问题.首先 $_
的内容需要转义,因为它可以包含二进制数据.其次,调用 echo
可能有点低效.
There are two problems here. First the content of $_
needs to be escaped as it can contain binary data. Second, invoking echo
might be slightly inefficient.
如何简单地将一些内容作为 STDIN 传送到 Perl 中的命令?
How can I simply pipe some content as STDIN to a command in Perl?
推荐答案
这个答案非常幼稚.它很容易陷入僵局.不要使用它!
This answer is a very naive approach. It's prone to deadlock. Don't use it!
如果父级向附加到子级 STDIN 的管道写入足够的数据,并且如果子级在从其 STDIN 读取之前向附加到其 STDOUT 的管道输出足够多的数据,则会出现死锁.(在某些系统上这可能只有 4KB.)解决方案涉及使用选择、线程等.更好的解决方案是使用已经为您解决问题的工具(IPC::Run3 或 IPC::跑步).IPC::Open2 和 IPC::Open3 级别太低,在大多数情况下没有用
我将保留原始答案,但鼓励读者从其他答案中选择解决方案.
I'll leave the original answer, but encourage readers to pick the solution from one of the other answers instead.
您可以使用 IPC::Open2open2> 读取和写入同一进程.
You can use open2
from IPC::Open2 to read and write to the same process.
现在你不需要关心逃避任何事情了.
Now you don't need to care about escaping anything.
use IPC::Open2;
use FileHandle;
my $writer = FileHandle->new;
my $reader = FileHandle->new;
my $pid = open2( $reader, $writer, 'wc -c' );
# write to the pipe
print $writer 'some content that need to be escaped &>|\"$\'`\s\\';
# tell it you're done
$writer->close;
# read the out of the pipe
my $line = <$reader>;
print $line;
这将打印 48
.
请注意,您不能对显示的确切输入使用双引号 ""
,因为反斜杠 \
的数量是错误的.
Note that you can't use double quotes ""
for the exact input you showed because the number of backslashes \
is wrong.
参见 perldoc open
和 perlipc 了解更多信息.
See perldoc open
and perlipc for more information.
这篇关于如何在 Perl 的 qx{} 语句中将变量的内容作为 STDIN 传送?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!