develooper Front page | perl.perl5.porters | Postings from January 2022

Re: Things you can't do in a signatured sub

Thread Previous | Thread Next
From:
Juerd Waalboer
Date:
January 23, 2022 20:17
Subject:
Re: Things you can't do in a signatured sub
Message ID:
20220123201654.GE7670@k
Paul "LeoNerd" Evans skribis 2022-01-19 17:59 (+0000):
>  * As a variant of the above; you can't even see the count of passed
>    arguments in order to distinguish no-argument from being explicitly
>    passed undef (or whatever the param default is)
>      sub signatured($x = undef) {
>        # impossible to distinguish signatured() from signatured(undef)
>      }

A simple workaround is possible by introducing a new undef-like value that has this very specific purpose:

     use Scalar::Util qw(refaddr);
     use constant NONE => \do { my $x };
     sub _provided($x) { ref($x) && refaddr($x) == refaddr(NONE) }

     sub bar($self, $new = NONE) {
         $self->{bar} = $new if _provided($new);
         $self->{bar};
     }

As checking arity for combined getter/setter methods is incredibly common, maybe it would make sense to have a very tiny module, maybe even core, that exports these, or to add them to Scalar::Util.

Of course, this depends on not using the constant for other purposes. I think that's mostly a matter of documenting that the behavior of any other use of the constant is undefined.
-- 
Met vriendelijke groet, // Kind regards, // Korajn salutojn,

Juerd Waalboer  <juerd@tnx.nl>
TNX

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About