如何在 Perl 的 qx{} 语句中将变量的内容作为 STDIN 传送? [英] How to pipe the content of a variable as STDIN in a qx{} statement in Perl?

查看:51
本文介绍了如何在 Perl 的 qx{} 语句中将变量的内容作为 STDIN 传送?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上想这样做:

$_ = "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 级别太低,在大多数情况下没有用

If the parent writes enough to the pipe attached to the child's STDIN, and if the child outputs enough to the pipe attached to its STDOUT before it reads from its STDIN, there will be a deadlock. (This can be as little as 4KB on some systems.) The solution involved using something like select, threads, etc. The better solution is to use a tool that has already solved the problem for you (IPC::Run3 or IPC::Run). IPC::Open2 and IPC::Open3 are too low-level to be useful in most circumstances

我将保留原始答案,但鼓励读者从其他答案中选择解决方案.

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 openperlipc 了解更多信息.

See perldoc open and perlipc for more information.

这篇关于如何在 Perl 的 qx{} 语句中将变量的内容作为 STDIN 传送?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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