Note that there are some explanatory texts on larger screens.

plurals
  1. POMoose (Perl): convert undef to empty string or 0 rather than die()
    primarykey
    data
    text
    <p>I've received <strong>a lot of exceptions</strong> from QA due to incomplete data being fed to my Moose constructors. The attribute name is present in the constructor arguments, but the value is <code>undef</code>.</p> <p>It's a fact of life with many scripting applications that things are just <code>undef</code>. And oftentimes this is perfectly fine. You don't want an annoying warning from the <code>warnings</code> pragma (so you do <code>no warnings 'uninitialized'</code>), and you certainly don't want your code to die because one little value, say the housenumber, is <code>undef</code>.</p> <p>So without further ado, I want my Moose constructors to behave like straight Perl (i.e. without <code>use warnings 'uninitialized'</code>), which is to convert <code>undef</code> to <code>0</code> or the empty string as required. The attempt shown in this sample does not work for the case where the attribute name is present but the value is <code>undef</code>. I could think of using <code>BUILDARGS</code> to achieve what I want. But is there a declarative way in plain Moose without <a href="https://stackoverflow.com/q/5823685/269126">resorting to MooseX::UndefTolerant</a> (which unfortunately I cannot use as it is not installed)? </p> <pre><code>package AAA; use Moose; has 'hu', is =&gt; 'ro', isa =&gt; 'Str'; has 'ba', is =&gt; 'ro', isa =&gt; 'Int'; no Moose; __PACKAGE__-&gt;meta-&gt;make_immutable; package BBB; use Moose; extends 'AAA'; has '+hu', default =&gt; ''; # don't want to die on undef has '+ba', default =&gt; 0; # idem no Moose; __PACKAGE__-&gt;meta-&gt;make_immutable; package main; use Test::More; use Test::Exception; # Those AAAs should die ... throws_ok { AAA-&gt;new( hu =&gt; undef ) } qr/Validation failed for 'Str' with value undef/; throws_ok { AAA-&gt;new( ba =&gt; undef ) } qr/Validation failed for 'Int' with value undef/; # .. but these BBBs should live: lives_ok { BBB-&gt;new( hu =&gt; undef ) } 'hu supplied as undef'; lives_ok { BBB-&gt;new( ba =&gt; undef ) } 'ba supplied as undef'; done_testing; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload