Q&A

Q1: It seems to me that for loops could be written as while loops, and vice versa.
A1: Yup, they sure could. If you wanted to strip all the constructs out of Perl that duplicate the behavior of other constructs, this could be one place where either one or the other would work. But there are some problems that are more easily thought of as number-of-times loops, as opposed to repeat-until-done loops. And being able to code the way you think is one of Perl's best features.
Q2:I tried to use continue to break out of a loop, and Perl spewed errors at me. What did I do wrong?
A2: C programmer, eh? You forgot that continue isn't used to break out of a loop in Perl (or you skipped that section). The equivalent of continue in Perl is next. Use continue as an optional block of statements to execute at the end of a block (see “Going Deeper.”)
Q3:I looked at your two examples of reading input from files, the one that uses $_ and the one that doesn't. The former is shorter, yes, but it's really hard to figure out what's going on if you don't know which operations are using $_. I'd rather use actual variables and avoid $_. I think it's worth a few extra characters if a script is more readable that way.
A3: That's definitely a philosophy to follow, and there are many Perl programmers that do follow that philosophy. And using the $_ variable willy-nilly to shorten a script can definitely make it much harder to read. But in some cases—reading input from <> being one of them—the use of $_ provides a common idiom in the language that when you get used to seems reasonable and easy to understand. If you have to read or modify other people's Perl scripts, chances are good you'll run into mysterious $_ behavior at some point.

Be aware of $_, use it where it's most appropriate, or avoid it if you feel it hurts readability. That's your choice.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.200.54