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

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

Thread Previous | Thread Next
From:
Ivan Vorontsov
Date:
September 3, 2023 10:28
Subject:
Re: //= and ||= in subroutine signatures
Message ID:
20230903132808.3e5269adcf3155e549257cad@yandex.ru
On Sun, 3 Sep 2023 10:32:00 +0100 Dave Mitchell <davem@iabyn.com> wrote:

> On Sun, Sep 03, 2023 at 11:48:14AM +0300, Ivan Vorontsov wrote:
> > With perl v5.38.0 I wrote a code similar to:
> >     perl -E 'sub foo ($x, $y //= 42, $z) {} foo(1, undef, 3)'
> > and got the error:
> >     Mandatory parameter follows optional parameter at -e line 1, near "$z) "
> > 
> > So //= and ||= mark a parameter as optional, but optional parameters
> > must follow mandatory ones. Outside of signatures these operators check
> > a value of a variable. A mandatory parameter can have undef or false
> > value. If it is feasible, maybe these operators could be applied to
> > mandatory parameters as well.
> 
> I don't see how that could work. It makes for an ambiguity.
> 
> You could create a parser rule which says that that if a mandatory
> parameter follows a ||= parameter, then the ||= should be interpreted as
> mandatory and vice versa:
> 
>     sub f1($x, $y ||= 1, $z)     {...}  # $y is mandatory
>     sub f2($x, $y ||= 1, $z = 1) {...}  # $y is optional
> 
> but then this becomes ambiguous:
> 
>     sub f3($x, $y ||= 1)         {...}  # is $y optional or mandatory?
> 
> -- 
> Please note that ash-trays are provided for the use of smokers,
> whereas the floor is provided for the use of all patrons.
>     -- Bill Royston

Maybe genuine optional parameters must be only the ones marked by =
sign. Others are mandatory. To mandatory parameters with //= or ||=
operators, that are last in the list or precede optional ones with =,
undef values are assigned, if there are less arguments than mandatory
parameters, and then operator works with that value.

-- 
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