nowox nowox - 1 month ago 7
Perl Question

How to pipe the content of a variable as STDIN in a qx{} statement in Perl?

I basically would like to do this:

$_ = "some content that need to be escaped &>|\"$\'`\s\\";
qx{echo $_ | foo}


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.

How can I simply pipe some content as STDIN to a command in Perl?

Answer

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;

This will print 48.

Note that you can't use double quotes "" for the exact input you showed because the number of backslashes \ is wrong.

See perldoc open and perlipc for more information.

Comments