nowox nowox - 1 year ago 76
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
might be slightly inefficient.

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

Answer Source

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

# 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download