Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi all, I have one file:
complex.12 .......... complex.10 ..........
i have taken the complex number on line 1 i.e. complex.12 need to match this in a second file and print the line on which complex.12 appears.
$line = $. if (m/$complex/);
however, not only does it match complex.12 in the second file but also complex.120/121 etc. How can i make the match more specific? Thanks

Replies are listed 'Best First'.
Re: pattern match
by davorg (Chancellor) on Oct 26, 2004 at 12:23 UTC

    Look for word boundaries.

    $line = $. if (m/\b$complex\b/);
    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: pattern match
by prasadbabu (Prior) on Oct 26, 2004 at 14:38 UTC

    You have mentioned that you want to match only complex.12 and not complex.120, so you can try this.

    You have not clearly mentioned that whether the number of digits vary, so you can try this

    undef $/;

    $file2 = <FILE>;
    if ($file2 =~ /complex\.\d{2}/) { $pre = $` $line = ($pre =~ s/\n/\n/g); print "$line"; }

    Prasad

      Your regexp would match both "complex.12" and "complex.120", because though it is only looking for "complex." followed by two digits, it doesn't exclude anything that exceeds the minimum criteria.

      Perhaps you meant to say:

      m/^complex\.\d{2}$/

      ...or...

      m/\bcomplex\.\d{2}(?!\d)/

      The first example requires that the string contain nothing at all besides "complex.nn" (where nn is two digits). The second example allows the string to contain additional stuff, but requires that the "complex.nn" tag be clearly bounded by a word boundry on the left, and a digit-boundry on the right.


      Dave

        ok thanks for your advice.

        "Every time we make mistake there is a lesson to learn." i have read this qoute somewhere. (which i follow)

        --Prasad

Re: pattern match
by Anonymous Monk on Oct 26, 2004 at 12:24 UTC
    sorry, thought of something $line = $. if (m/$complex\D+/);