develooper Front page | perl.perl5.porters | Postings from February 2019

Re: New defined-match operator

Thread Previous | Thread Next
From:
Aristotle Pagaltzis
Date:
February 21, 2019 18:49
Subject:
Re: New defined-match operator
Message ID:
20190221184941.GA9464@plasmasturm.org
* David Cantrell <david@cantrell.org.uk> [2019-02-21 13:25]:
> We all know how convenient it is to write this:
>
>   $foo //= 'bar';
>
> instead of:
>
>   $foo = 'bar' unless(defined($foo));
>
> Well, wouldn't it be nice to be able to write this:
>
>   if($foo //~ /bar/)

That syntax already parses.

> instead of:
>
>   if(defined($foo) && $foo =~ /bar/)

You can avoid mentioning $foo twice by writing

    if ( grep /bar/, $foo // () )

Or if that feels too subtle and/or you want to run on 5.8:

    if ( grep defined && /bar/, $foo )

> Thoughts?

Agree with Paul’s “punctuation soup” verdict.

What is really needed is not dozens of one-off “but only when the value
is undefined” variants of existing operators, but simply a unary logical
operator that short-circuits out of an expression when its argument is
undefined. Basically

    if ( ensure_defined($foo) =~ /bar/ )

That would cover all sorts of other cases like

    ensure_defined($foo)->bar

But it can’t be this particular design because that gets ugly fast:

    ensure_defined(ensure_defined(ensure_defined($foo)->bar)->baz)->quux

I guess it would have to be the right punctuation with the exact right
precedence level to make it properly useful. Maybe. Un/fortunately we
don’t have a Larry around here who has the chops for such a job.


* Uri Guttman <uri@stemsystems.com> [2019-02-21 18:48]:
> what about this:
>
> ($foo //= '') =~ /bar/ ;
>
> the goal is to eliminate the undef warning. you can put any default
> value for the null string. this is easy to write and read and no new
> op is needed.

No idea why you used //= instead of //, which can’t be the desired
choice, but anyway this also doesn’t short-circuit the match, which OT1H
is a waste of time and OTOH means that if the pattern can match the
empty string then this construct will give the opposite answer for
undefined values than Dave’s code or my alternatives based on `grep`.


Regards,
-- 
Aristotle Pagaltzis // <http://plasmasturm.org/>

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