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

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

Thread Previous | Thread Next
Dave Mitchell
January 31, 2022 21:08
Re: Things you can't do in a signatured sub
Message ID:
On Mon, Jan 24, 2022 at 07:01:46AM +0000, Ovid via perl5-porters wrote:
> You've sort of turned @_ into @maybe_x and now you can pass 20 arguments to it, killing one of the strongest features of signatures. Both your example and @_ are to attempts to determine how many arguments were passed to a sub. Imagine if we had a $^NUM_ARGS variable (terrible name, though I think someone else suggested it):
>     sub name ( $self, $name=undef ) {
>         if ( $^NUM_ARGS == 2) {
>             $self->{name} = $name; # even if undef
>         }
>         else {
>             return $self->{name};
>         }
>     }
> By decoupling the signature from knowing how many args are passed, the solutions is much cleaner and we can't pass 20 arguments to the sub.

Again, with query parameters this is simple:

     sub name ($self, ??$has_value, $value = undef) {
         if ($has_value) {
             $self->{name} = $value; # even if undef
         else {
             return $self->{name};

$has_value is a boolean value which is true if there are any args
remaining at that point in parameter processing.

Dave's first rule of Opera:
If something needs saying, say it: don't warble it.

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About