I'm stuck trying to figure out why my usage of IPC::Open2 isn't working how I expect.

This works:

perl -e 'package MyPack; sub foo { use IPC::Open2; my ($in, $out); my $pid = open2($out, $in, q[program --unbuffered]); print $in q|some json|; my $result = <$out>; warn "got [$result]\n"; close($in); close($out); waitpid($pid, 0); } 1; package Main; MyPack->foo();'

It prints my expected result in square brackets after taking some time to calculate the result.

But if I have lib/MyPack.pm:

package MyPack; sub foo { use IPC::Open2; my ($in, $out); my $pid = open2($out, $in, q +[program --unbuffered]); print $in q|some json|; my $result = <$out>; + warn "got [$result]\n"; close($in); close($out); waitpid($pid, 0); } 1;

and do:

perl -Ilib -MMyPack -e 'MyPack->foo();'

It returns immediately with an empty result set (json empty square brackets inside my printed square brackets). foo() in both cases is copy/pasted. Why doesn't it work from inside a .pm?

Edit for more: Fully copy/pasting the entire contents of the perl 1 liner that works in to lib2/MyPack.pm, and then calling:

perl -Ilib2 -e 'use MyPack;'

also doesn't work. What can it be about having the code inside a .pm that could stop it working?

Edit for solution: my input json string had single quotes, which behaved differently on the command line and inside a .pl or .pm. Removing the quotes made them both behave the same.


In reply to Why is IPC::Open2 behaving differently in a .pm? by sendu

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.