I try to avoid the use of $1, $2 etc.

I find it better and easier as far as the coding, to put the left hand side of the regex match into a list context and for example assign $catalog_num directly instead of fiddling with $1!

#!/usr/bin/perl -w use strict; my @lines = ( 'Catalog Number: PAL1001', ' Catalog Number:PAL1001', 'Catalog Number: Catalog Number: PAL1001', 'Catalog Number: PAL1001Catalog Number: PAL1001', 'Cat Number: PAL1001Catalog', 'Catalog Number: 123PAL100'); foreach my $line (@lines) { my ($catalog_num) = $line =~ /^\s*Catalog Number:\s*([A-Za-z]+\d+)/ +; if ($catalog_num) { print "$catalog_num\n" } else { print "Bad Line!...$line\n"; } } __END__ PAL1001 PAL1001 Bad Line!...Catalog Number: Catalog Number: PAL1001 PAL1001 Bad Line!...Cat Number: PAL1001Catalog Bad Line!...Catalog Number: 123PAL100
Update:
When writing if statements like above, you have to consider "truth-ness". $catalog_num is false if that value is undefined or it is numeric zero. And that's a "Bad Line!"

In the above, a valid catalog_num cannot be a numeric zero and so I can just test "if ($catalog_num)" instead of "if (defined $catalog_num)".


In reply to Re: parsing hmtl file with regex by Marshall
in thread parsing hmtl file with regex by PanchoAguirre

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.