Q&A

Q1: You've discussed efficiency a lot in this chapter, but as far as I can see, all my programs run in the blink of an eye. Is efficiency really worth worrying about?
A1: It depends. When you're using Perl to process example data, efficiency probably doesn't make a difference. When your Perl program has to process a 5 gigabyte Web log, it's worthwhile to cash in on any time savings that coding for efficiency can afford you. Perl is a language that's perfect for batch processing, and in the world of batch processing, every millisecond often counts.
Q2:I have a bit of code that uses a two-step process to extract something out of a string. The first pattern puts a substring into $1, and then the second pattern searches $1 for a different pattern. The second pattern never matches, and printing $1 shows that it's empty. But if it was empty, the second pattern shouldn't have even been tried in the first place. What's going on here?
A2: It sounds like you're trying something like this:
if ($string =~ /some long pattern with a {subpattern}  in it/) {
   if ($1 =~ /some second pattern/) {
      # process second pattern
   }
}

Unfortunately, you can't do that. The $1 variable (or any other variable) is incredibly temporary. Each time you use a regular expression, Perl resets all the match variables. So, for this particular example, the first line does match and fills $1 with the contents of the parentheses. However, the minute you try another pattern-match (in the second line), the value of $1 disappears, which means that second pattern can never match.

The secret here is simply to make sure you put the values of any match variables somewhere else if you want to use them again. In this particular case, just adding a temporary variable and searching it instead will work just fine:

if ($string =~ /some long pattern with a {subpattern}  in it/) {
   $tmp = $1;
   if ($tmp =~ /some second pattern/) {
      # process second pattern
   }
}

Q3:I've seen some scripts that set a $* variable to 1 to do multiline matching, similarly to the way you described the /m option. What's $*, and should I be using it?
A3: In earlier versions of Perl, you set the $* to tell Perl to change the meaning of ^ and $. In current versions of Perl, you should be using /m instead; $* is only there for backwards compatibility.
..................Content has been hidden....................

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