Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: Exiting subroutine via next (that old chestnut)

by Roy Johnson (Monsignor)
on Mar 04, 2008 at 17:13 UTC ( [id://671941]=note: print w/replies, xml ) Need Help??


in reply to Exiting subroutine via next (that old chestnut)

The test for empty line has nothing to do with removing comments, so there's no need to check for it in the sub. I'd reverse the test and do away with the next:
sub RemoveComments { my $line=$_[0]; $$line =~ s/#.*$//; # No need for a separate pattern match } .... while ($temp=<INPUT>){ RemoveComments(\$temp); if ($temp =~ /\S/){ ... some other code ... } }
but you could also do
while ($temp=<INPUT>){ RemoveComments(\$temp); next if ($temp !~ /\S/); ... some other code ... }

Caution: Contents may have been coded under pressure.

Replies are listed 'Best First'.
Re^2: Exiting subroutine via next (that old chestnut)
by why_bird (Pilgrim) on Mar 04, 2008 at 17:28 UTC
    Thanks all, I'll change it, even if I don't like it as much. I can probably live with one or two more lines of code. I suppose there is a good reason for it throwing a warning at me.. *sigh* :)
    ........
    Those are my principles. If you don't like them I have others.
    -- Groucho Marx
    .......
      Thanks all, I'll change it, even if I don't like it as much. I can probably live with one or two more lines of code. I suppose there is a good reason for it throwing a warning at me.. *sigh* :)
      It's good practice to never alter the control of a loop externally like that--it makes your subroutine very tightly coupled to that one specific usage, and in fact will blow things up if used differently. Functions should make it easier for you to reuse code in multiple contexts; it's one of their main reasons for existing. Most languages wouldn't even let you put a loop control variable in a sub like that (I know that's not entirely relevant, but just FYI) and Perl is reluctant to do so as well. Other people who may see your code in the future won't be expecting behavior like that.

      I think the first reply's solution, using and, is an elegant alternative, and makes it possible to tell what is going on just by looking at the loop code.

      My 2 cents!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (5)
As of 2024-04-24 20:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found