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

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

Thread Previous | Thread Next
Ovid via perl5-porters
January 24, 2022 07:01
Re: Things you can't do in a signatured sub
Message ID:
On Monday, 24 January 2022, 07:50:33 CET, Darren Duncan <> wrote:

> I still oppose as wrong-headed the concept of using such sentinel default values 
> to try and detect when no argument is passed.  The only use of such default 
> values is when you don't care to distinguish between users explicitly passing 
> that value from them not passing anything.  When you actually want to 
> distinguish them not passing a value, DON'T use defaults, and instead use "@" to 
> capture the list and test the list for presence of an element. -- Darren Duncan

Then how do we fix the issue? What we *want* to know is how many arguments were passed to a variadic sub. You have this as an earlier example:

    sub signatured(@maybe_x) {
        if (scalar @maybe_x > 0) {
            # we were given an argument, which may or may not be undef
        else {
            # we were not given an argument

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.

IT consulting, training, specializing in Perl, databases, and agile development 

Buy my book! -

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