ag4ve has asked for the wisdom of the Perl Monks concerning the following question:

I'm not sure what I'm doing wrong here (or why this is reporting success as I'm not getting any output). The end goal is to echo an array of iptables save data into iptables-restore:

#!/usr/bin/env perl use strict; use warnings; use Data::Dumper; use IPC::Cmd qw/run/; my @in = ("Test foo", "Test bar"); print "In: " . Dumper(@in); my @out = run(command => 'echo -n ', \@in , '| sed -r "s/(foo|bar)/pass/"'); print "Out: " . Dumper(@out);

Output:

In: $VAR1 = 'Test foo'; $VAR2 = 'Test bar'; Out: $VAR1 = 1; $VAR2 = undef; $VAR3 = []; $VAR4 = []; $VAR5 = [];

UPDATE:

IPC::Run does work as @runrig said - I just didn't notice -r got removed from said which changes the regex sed uses.

#!/usr/bin/env perl use strict; use warnings; use Data::Dumper; use IPC::Run qw/run/; use IPC::Run qw(run); my @in = ("Test foo", "Test bar"); run [echo => -n => join("\n", @in)] , '|', [ sed => -r => "s/(foo|bar) +/pass/" ], '>', \my $out; print "Redir: " . Dumper($out);

Replies are listed 'Best First'.
Re: IPC::Cmd pipe array
by runrig (Abbot) on Oct 28, 2013 at 22:38 UTC
    IPC::Cmd's command option takes one string or array reference that specifies your command. Since you have a pipe "|" in your command(s), you are stuck with specifying a string. Or you can try IPC::Run
    use IPC::Run qw(run); my @in = ("Test foo", "Test bar"); run [echo => -n => @in] , '|', [ sed => "s/(foo|bar)/pass/" ], '>', \m +y $out;

      That sorta works (ie, it doesn't error), but not really:

      #!/usr/bin/env perl use strict; use warnings; use Data::Dumper; use IPC::Cmd qw/run/; my @in = ("Test foo", "Test bar"); print "In: " . Dumper(@in); @in = ("Test foo", "Test bar"); my @out = run(command => [echo => -n => @in] , '|', [ sed => -r => "s/ +(foo|bar)/pass/" ], '>', \my $out); print "Out: " . Dumper(@out); print "Redir: " . Dumper($out);

      Out:

      % ./t2.pl In: $VAR1 = 'Test foo'; $VAR2 = 'Test bar'; Out: $VAR1 = 1; $VAR2 = undef; $VAR3 = [ 'Test foo Test bar' ]; $VAR4 = [ 'Test foo Test bar' ]; $VAR5 = []; Redir: $VAR1 = undef;
        My code is using IPC::Run, not IPC::Cmd. Your's is still using IPC::Cmd.