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

Re: New defined-match operator

Thread Previous | Thread Next
Aristotle Pagaltzis
February 21, 2019 18:49
Re: New defined-match operator
Message ID:
* David Cantrell <> [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


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


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 <> [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`.

Aristotle Pagaltzis // <>

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