Question

I suppose this question may strike some as not very important, but I have been wondering why there is no low-precedence defined-or operator in Perl. I suppose there is a reason, since perlop explicitely mentions the fact.

One instance where I would think it useful is in such a subroutine:

sub input_many_data {
    my $x = <> // return;
    do_some_processing_with($x);
    my $y = <> // return;
    do_some_processing_with($y);
    return ( $x, $y );
}

while (1) {
    my ( $x, $y ) = &input_many_data or last;
    do_something_with( $x, $y );
}

It does work with $x = (<> // return), but the purpose would be much more obvious, and the code more readable and less error-prone, with something like ($x = <>) dor return.

Was it helpful?

Solution

I never really understood why some porters[1] had a problem with it. I think there was a lack of consensus about what to call it (definedor, dor, err), but in retrospect, I'd be tempted to believe the true reason is a lack of comfort with use feature. Keep in mind that use feature and // were added to Perl in the same version.

Or maybe not. You can find the conversation on the p5 porters mailing list.


By the way, the intent of the following is quite obvious:

my $x = <>
   // return;

It's a bad practice to hide a return at the end of a line anyway. Alternatives are:

( my $x = <> )
   // return;

defined( my $x = <> )
   or return;

my $x = <>;
$x // return;

my $x = <>;
return if !defined($x);

Those of those are compatible with commonly used 5.8.


  1. Those who work on Perl itself.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top