Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

For clarity and cleanliness, I'd recommend...

by TheDamian (Priest)
on Mar 05, 2005 at 19:31 UTC ( #436949=note: print w/ replies, xml ) Need Help??


in reply to looking for a good idiom: return this if this is true

if (my $result = thatroutine()) { return $result; }


Comment on For clarity and cleanliness, I'd recommend...
Download Code
Re: For clarity and cleanliness, I'd recommend...
by merlyn (Sage) on Mar 05, 2005 at 19:40 UTC

      This works fine, and does not clobber $_.

      #!/usr/bin/perl -w use strict; print test(), $/; sub subtest { return 4 } sub test { return $_ if ( local $_ = subtest() ); # continue return 'false'; }
Re: For clarity and cleanliness, I'd recommend...
by xdg (Monsignor) on Mar 06, 2005 at 14:52 UTC

    Given how often I hear about (even experienced) programmers mistakenly typing "=" in an if statement when they meant "==", I don't know if encouraging this particular idiom as a rare case where it is indeed what you mean is a good idea. Might I suggest this instead:

    while (my $result = thatroutine()) { return $result; }

    As an aside, I was actually surprised that the version with if didn't warn about the single "=", but a little testing showed that the warning only appears to happen if you mistakenly assign (instead of compare) a literal value, not a subroutine.

    -xdg

    Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

      I agree with you. I would certainly never recommend that people write:
      if ($result = thatroutine()) { return $result; }
      But, as your while-based variant shows, non-constant assignments in a conditional are always fine if you're declaring the lvalue variable at that point:
      if (my $result = thatroutine()) { return $result; }
      In such cases, the = must be intentional, since == on a newly-created variable doesn't make any sense.

      As for your alternative suggestion, I don't feel it's a clear or as clean as using an if, because the use of a while implies looping behaviour, which the return undermines in a not-entirely-obvious way. That could be especially misleading to subsequent readers of the code if the number of statements in the while block later increases, pushing the return away from the loop keyword it's subverting.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://436949]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (11)
As of 2014-09-19 10:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (135 votes), past polls