You can use overload to simulate this behavior. But SetDualVar lets you build scalars the same way that $! is built, which it quite a bit less overhead (as if that matters). The module lets you set both the numeric and string value of a scalar without the two having to agree.

Note that tie can't distinguish string and numeric "sub-contexts" and so isn't enough by itself to accomplish this. But you can use tie in conjunction with either overload or SetDualVar to do this (or just use overload by itself).

And, if you really want to have it act just like $!, then a handy way to look up error strings from error numbers:

sub getErrorText { local( $! )= 0+shift(@_); return "$!"; }

But that also made me realize that you don't even need a module to create a dual-valued scalar that duplicates $! since

$errno= $!= 5; print 0+$errno," $errno\n";
prints something like "5 Input/output error".

Also note that getting the type of "copy semantics" you want may be the determining factor in which method to use.

        - tye (but my friends call me "Tye")

In reply to (tye)Re: $! context behavior by tye
in thread $! context behavior by eak

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.