in reply to Re^2: Regular expression match in code
in thread Regular expression match in code
my $var = "62.40.40.30"; print "var: $var\n"; ## Please note that following part of code (foreach, if ## exists, while) doesn't work ## It doesn't give any error; simply says no match foreach $str (@bigArray) { print "$str\n"; if ($str =~ /^$var/) { print "IP address matched. Proceed to log trap!\n"; last; } else { print "Match not found.\n"; } }
You iterate over all values in the array. Since one of the items in the array matches the regex, you get one line of output saying IP address matched. Proceed to log trap, and for all items before the match you get the output that no match was found.
If you don't want that output even though you can match later on, then don't print it. Only print it if the iteration is finished, and you didn't find any matches.
if (exists ($hashArray{$var})) { print $var . " exists in hash!\n"; } while (($key, $value) = each (%hashArray)) { print "KEY: $key\n"; if ($key eq $var) { print "IP Matches!\n"; } }
A hash is a better approach to what you try to do, but you do it overly complicated. Instead of iterating over it, you can get the value straigt out of the hash:
if (exists ($hashArray{$var})){ print "$var exists in the hash.\n"; print "Its value is $hashArray{$var}\n"; }
Whenever you iterate over a hash to see if the key is in there, you're doing something wrong.
So with all three methods you actually find the IP you are looking for (and using the hash access is the easiest and most straight forward).
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Regular expression match in code
by truptivk (Novice) on May 12, 2010 at 09:06 UTC | |
by moritz (Cardinal) on May 12, 2010 at 09:24 UTC | |
by truptivk (Novice) on May 12, 2010 at 09:45 UTC | |
by moritz (Cardinal) on May 12, 2010 at 10:08 UTC | |
by AnomalousMonk (Archbishop) on May 12, 2010 at 20:48 UTC | |
by truptivk (Novice) on May 13, 2010 at 09:16 UTC | |
by ig (Vicar) on May 12, 2010 at 09:20 UTC |