Hi Ken,

Just to pick up on what the AM mentioned: properly closeing a piped open is important so one can catch all possible errors (as opposed to closeing regular files, where in my experience things go wrong much less often). I see you used autodie, but as far as I can tell it doesn't catch errors when the filehandle is implicitly closed when it goes out of scope.

In your code, if I replace the command with something that returns a nonzero exit code, and add the close at the end of the sub, I get confusing results: inside of capture, the error doesn't seem to get caught at all, and outside of capture, I get the confusing error message "Can't close(GLOB(0x8e2b62)) filehandle: '' at ...". (In fact, if I remember correctly, strange interactions with autodie and piped opens is one of the reasons I started avoiding autodie.)

So here's the same run_external_command code, without autodie but with the minimum error handling:

my $extcmd = 'cat'; open my $cmd_pipe, '|-', $extcmd or die "open $extcmd: $!"; print $cmd_pipe "password\n"; close $cmd_pipe or die "close $extcmd: ".($! ? $! : "\$?=$?");

However, nowadays I very much prefer to use more better-suited modules, one of my favorites is IPC::Run3. For the OP:

use IPC::Run3 'run3'; my $stdin = "password\n"; my @extcmd = ('cat'); run3 \@extcmd, \$stdin, \my $stdout, \my $stderr or die "run3 failed"; $? and die "run3: \$?=$?"; print "stdout: <<$stdout>>\n"; print "stderr: <<$stderr>>\n";

Regards,
-- Hauke D


In reply to Re^2: How to pass data as STDIN to Capture::Tiny by haukex
in thread How to pass data as STDIN to Capture::Tiny by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.