develooper Front page | perl.perl5.porters | Postings from September 2023

Re: //= and ||= in subroutine signatures

Thread Previous | Thread Next
From:
Ivan Vorontsov
Date:
September 5, 2023 19:55
Subject:
Re: //= and ||= in subroutine signatures
Message ID:
20230905225546.5f50bcfbb197608468472988@yandex.ru
On Mon, 4 Sep 2023 16:44:13 +0100 Dave Mitchell <davem@iabyn.com> wrote:

> On Mon, Sep 04, 2023 at 06:25:57PM +0300, Ivan Vorontsov wrote:
> > >     f($x, $y //= 1,  $z = 2)    # $y is optional parameter
> > 
> > This is an intermediate case. To a caller $y is optional, but $y
> > must have undef value either explicitly or implicitly to trigger the
> > assignment, $z must not accept argument at all to get assigned. I would
> > call $y semi-optional :)
> 
> I don't understand what you are trying to say there. The difference
> between a mandatory and optional argument is that perl will croak() 
> if not enough  mandatory arguments are passed to the function.

Sorry for confusion. $y is optional. I called $y semi-optional
jokingly. It's hard to joke in a foreign language. Won't try to do it
again.

But I tried to underline that //= operator demands a value to be
checked. With optional parameters to trigger checked assignment to $y,
it must get value undef either explicitly f('foo', undef) or implicitly
f('foo'). With mandatory parameters (as in hypothetical
sub foo ($x, $y //= 42, $z) {}) $y must always get explicit value through
an argument which might happen to be undef, then checked assignment
triggers.

Consider this example:
    # $v, $w, $x are mandatory; $y, $z are optional
    sub bar ($v, $w, $x, $y //= 1, $z = 2) {
        $w //= 42;
    }
Wouldn't it be convenient to write as:
    # $v, $w, $x are mandatory; $y, $z are optional
    sub bar ($v, $w //= 42, $x, $y //= 1, $z = 2) {
    }
But I suppose it can't be done. It's fine.

> Given
> 
>     f($x, $y //= 1,  $z = 2)    # $y is optional parameter
> 
> what do you expect the result to be for each of these (i.e. croak, or $y
> assigned the value 2, or whatever)?
> 
>     f(1);
>     f(1,2);
>     f(1, undef);
>     f(1, 2, undef);

They must work as documentation says.
 
    f(1);           # $x = 1, $y = 1, $z = 2
    f(1,2);         # $x = 1, $y = 2, $z = 2
    f(1, undef);    # $x = 1, $y = 1, $z = 2
    f(1, 2, undef); # $x = 1, $y = 2, $z = undef

-- 
Ivan Vorontsov <ivrntsv@yandex.ru>

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