Hi, the first problem is that your two loops are the wrong way round: you want to read each line once (in the outer loop), than examine that line against each of the possible patterns (in the inner loop).

The second problem is that you are reading the lines from the file into the default variable ($_), but then processing as if it had been read into $pattern. ("Pattern" is also an unexpected name for it - in usual terminology, the pattern would be the regular expression, and we'd talk about "matching a string against a pattern".)

I'd also recommend using a different delimiter for the pattern such as {...} so that you don't need to escape the literal '/' characters in the pattern, and using a variable like $fh for the filehandle in preference to a bareword "FH".

So I'd suggest something like this:

use strict; # always use warnings; # always my $file = "/home/test.txt"; if (-e $file) { my @list = ("Anls", "core", "route"); open(my $fh, '<', $file) or die "$file: $!"; while (my $line = <$fh>) { foreach my $x (@list) { if ($line =~ m{$x/(.*)/(.*)}) { my $version = $1; print "$x: $version\n"; } } } close $fh; }

Update: just after posting, it occurs to me that it is quite likely that you intend a line like "score/01.00/windows" not to match your "core" pattern. If I'm correct, then the pattern should additionally be anchored to the start of the string:

      if ($line =~ m{^$x/(.*)/(.*)}) {

In reply to Re: Pattern matching in perl by hv
in thread Pattern matching in perl by noviceuser

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.