in reply to return if defined

sub my_find_or_create { # ... return $self->find_by_something(@args) // do { # ... }; }
perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

Replies are listed 'Best First'.
Re^2: return if defined
by Anonymous Monk on Dec 20, 2012 at 13:11 UTC

    Clever, but maybe a little too clever.

    This isn't the clearest construct in the world to begin with, and it especially has the potential to be confusing if the code within the do block is long. In that case, the last statement of the block is implicitly returned by the block and used as the return value, but it is a long way from the return statement itself.

    You could do the exact same thing a lot more clearly just by using a subroutine.

    sub my_find_or_create { # ... return $self->find_by_something(@args) // $self->create_new(@args); }
      Clever, but maybe a little too clever. This isn't the clearest construct in the world ...

      But I thought the whole point of the OP was to be too clever by half, and clarity be damned.

      IMHO, the pair of statements
          my $existing_result = $self->find_by_something(@args);
          return $existing_result if (defined $existing_result);
      is perfectly clear and sufficiently unclever to help me avoid future foot trauma.