We are all used to checking $! in error messages after failed system calls. However when you reap a child you may know the return code (it is in $?), but would still like to get the system message. For instance the return is 2 and you would like to see No such file or directory. How can you get the translation?

The secret involves some deep magic of $! that is documented in perlvar. It is different when being treated as a string and a number. You can assign the numerical return code, and when used as a string it will have the text of the message. (If the return is being used as a string, there is no need to coerce it like I did. But enough magic is going on that I *prefer* doing that.)

# Turns numerical return codes into text. See perlvar. sub get_system_error { local $! = shift; return "$!"; } print "$_: ", get_system_error($_), "\n" foreach 1..50;

In reply to Populate $! by tilly

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.