Re: How to test result of an extraction?



Ravi Malghan am Donnerstag, 27. April 2006 19.52:

Hello Ravi

(please start a new thread for a new question)

Hi: I am extracting some value from $complete_event as
follows. What can I check to see if the extraction
returned a valid value? "if($_)" seems to be giving
incorrect values.

look at perldoc perlvar for the meaning of the $_ var.
It's not what you want in your case below.

You're more interested in the question "What can I check to see if the
extraction succeeded?";
if the extracted value is valid or not is a secondary problem and is
implementation specific.

In the following statement, $srcIp
is being set to an old extracted value if there is no
valid value following srcIP in my $complete_string
instead of 0.

True; from perldoc perlre:

"NOTE: failed matches in Perl do not reset the match variables, which makes it
easier to write code that tests for a series of more specific cases and
remembers the best match."

$complete_event =~ /srcIp=(.+) srcPort=/;
if($_) {$srcIp = $1;}
else {$srcIp = 0;}

Only use $1 etc. if the match succeeded:

if ($complete_event =~ /srcIp=(.+) srcPort=/) {
if($1) {$srcIp = $1;}
else {$srcIp = 0;}
}

or shorter

my $srcIp=$1 ? $1 : 0
if $complete_event =~ /srcIp=(.+) srcPort=/;

Eventually you also want to be more specific in what is a valid value to
extract, at least ([\d.]+) instead of (.+) .

hope this helps

Dani
.