Soft call operator: ~> (thoughts)

Hey.

And I’ve been thinking about the idea of ​​a “soft call” for a long time. Even when writing in ASM always irritated exceptions when CALL 0

Well, here again returned to this topic.

What’s wrong? Very often I have to write the following code:

my $ x; my $ y;
If( ($x = $ obj-> method) && ($y = $x->another_method) ) {
    $ y = ...;
}

An example from life:

If ($ db-> query (...) -> hash -> {value}) {...}
If ($ db-> resultset ('table') -> search (...) -> related_resultset ('table2') {...}

Here if the query returned an empty result, the code will fall.

But when you use a soft call operator, you can not be afraid of exceptions and the code will become easier:

use pragma 'soft_call';

If( my $ x = $ obj-> method ~> another_method ) {...}

If ($db-> query (...) ~> hash -> {value}) {...}

If( $db-> resultset ('table') -> search (...) ~> related_resultset ('table2') {...}

And it seems like everything is expressive.

Even the very implementation of the pragma in a dozen lines:

  1. make a plug-in for keyword, like Syntax :: Keyword :: Try
  2. cling to http://perldoc.perl.org/perlguts.html#Pluggable-runops
  3. Pseudocode

.

sub soft_call_operator {

    my ($ left_operand, $ right_operand) = @_;

    return undef if! defined $left_operand;

    # Do normal processing of the function call
    '->'($left_operand, $right_operand); 
}

I try to google existing analogues and found the Postgres when RETURNS NULL ON NULL INPUT

Comments Wellcome

UPD Thank to choroba for the link. This theme was discussed here

2 Comments

> I try to google existing analogues

We actually have safecall operator (.?) in Perl 6. It looks if an object .^can() call the provided method and returns Nil if it can't.

It's not very versatile, because of the stuff a Nil type inherits, some of the methods you CAN call on it, but the call still fails because of type restrictions on those methods, so the whole thing goes crashing anyway.

I guess Perl 5 isn't affected as much, since `undef` isn't an object, but I encourage you to think up of cases where it might end up being one...

Leave a comment

About KES

user-pic I blog about Perl.