Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

Re-read the documentation in perlsub (Link updated; thanks ikegami.) and you will see two big red flags. First:

If no return is found and if the last statement is an expression, its value is returned.

In this construct: my $val = do { if(0){1} };, the last statement evaluated is the conditional, which is numeric zero, so $val gets 0. Had the conditional been true, the last expression evaluated would be the last one in the if statement's block (1, in this case). So unless you explicitly specify an "else" condition, your last expression will be the conditional from the if() statement, if that condition proves false.

The next red flag:

If the last statement is a loop control structure like a foreach or a while , the returned value is unspecified.

So now if your conditional looks like this: my $val = do { if( 1 ) { for( 0 ) { $_ } } };, all bets are off; the behavior is unspecified: You might get a '0' (the last expression), or not... or your keyboard may burst into flames, though Perl isn't prone to doing that under most circumstances. ;)

do{}; blocks can be thought of as immediate-execution subroutines, with implicit(-only) return values.

This tricky behavior is the reason for the recommended ban on "Implicit Returns" in Perl Best Practices (page 197).


Dave


In reply to Re: return value of "if" (documentation?) by davido
in thread return value of "if" (documentation?) by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (4)
As of 2024-04-25 15:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found