The split technique, as pointed out above, is certainly much more compact, but you now have to check explicitly that the last two elements are numeric:

if (my @match = split /\s+/) { if ($match[-2] =~ /^\d{1,3}$/ and $match[-1] !~ /\D/) { $match[-2] = $count++; } $_ = "@match\n"; }

(Note that it's easier to say that the last element doesn't match a non-digit...). Also, with an array, it doesn't matter if you capture one more or less; the code will adapt to the change.

Otherwise, if for some reason you needed to stay with the regular expression as posted (for instance, because you really didn't want to capture the 12th element or something), the following pattern is equivalent (repetitive stuff in the middle omitted) to yours, and less noisy:

/([^ ]+)\s+([^ ]+)\s+([^ ]+)...\s+(\d{1,3})\s+(\d+)$/

that is, you don't need to group \s+. And I suspect you may want \S+ rather than [^ ]+:

/(\S+)\s+(\S+)\s+(\S+)\s+...\s+(\d{1,3})\s+(\d+)$/

You could also have Perl build the pattern for you, rather than mess with the fiddly details:

my $pat = join ( '\\s+', ( ('(\\S+)' x 15), '(\\d{1,3})', '(\\d+)', )); $pat = qr/\A$pat\z/;

• another intruder with the mooring in the heart of the Perl


In reply to Re: seeking improvement in my smiple program using regular expression by grinder
in thread seeking improvement in my smiple program using regular expression by convenientstore

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.