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).

Perl 6 - links to (nearly) everything that is Perl 6.

In reply to Re^3: Regular expression match in code by moritz
in thread Regular expression match in code by truptivk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.