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

Is there a way to print a variable to a system() command.
Something like this (pseudo code) :
$x = "..multiline text.."; print qx{ echo $x | mail -s '123' email@at.com};

I don't want to capture the output of a cmd, but rather pipe multiline text to a command.

Replies are listed 'Best First'.
Re: $var | system()
by kennethk (Abbot) on Sep 05, 2012 at 16:34 UTC
    If by "multiline text" you mean feed it input via STDIN, you can explicitly open a pipe using open, e.g.
    open my $stream, "| mail -s '123' email\@at.com" or die "pipe fail: $! +"; print $stream $text; # Or @lines, or $line1, $line2... close $stream; # Handle needs to close or go out of scope to clear buf +fer and send EOF

    There are a large number of other possibilities here, depending on how complex you want to get: system; pipe, fork and exec; IPC::Open2; IPC::Open3... See perlipc for some gory detail.


    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

Re: $var | system()
by choroba (Cardinal) on Sep 05, 2012 at 16:04 UTC
    If the text does not contain single quotes, you can just quote it:
    my $x = "..multiline\ntext.."; print qx{ echo '$x' | sed 's/^/> /'};
    For more complicated strings, you can use
    my $x = qq(..multiline\ntext.."'); open my $CMD, '|-', q{sed 's/^/> /'} or die $!; print {$CMD} $x; close $CMD;
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ