[ale] perl regexp question de'jour ;-)

JK jknapka at kneuro.net
Fri Jul 7 18:15:01 EDT 2006


JK wrote:

>Jim Popovitch wrote:
>
>  
>
>>My problem is this:  Perl regexp matching seems to not be flexible (or 
>>my understanding of perl and/or regexp matching isn't broad enough) in 
>>that it doesn't allow me to specify a match condition for more 
>>parameters than actually exist.  The above code will work as long as 
>>there are at least 2 params following the keyword "alert".  If I use the 
>>following code, then option lines with less than 3 parameters are skipped.
>>
>>   ------------------------
>>   }
>>   elsif ($ln =~ /^alert\s(\S+)\s(\S+)\s(\S+)/i) {
>>      my $email = $1
>>      my $interval = $2
>>      my $priority = $3
>>      ....
>>   }
>>   ------------------------
>>
>>Any examples on how to use perl regexp matching against a variable 
>>number of parameters?
>> 
>>
>>    
>>
>If they're always going to be whitespace-delimited, I'd just
>use split, instead of messing with regexps.
>  
>
To clarify, my approach would be something like this (pseudocode):

for line in input {
  words=split(line);
  if words[0]='alert' {
    handleAlert(words);
  } elsif (word[0]=='someOtherToken') {
    handleSomeOtherToken(words);
  }
}

Etc. Or perhaps even more flexible, assuming Perl
lets you call a function given its name as a string:

for line in input {
  words=split(line);
  callFuncByName("handle"+words[0],words);
}

You might need some initial processing to eg throw
away comments, but the loop above works for
many config file formats, in my experience.
I usually do it in Python, though.

-- JK




More information about the Ale mailing list