in reply to RE: Re: Why regular expression so hard?!
in thread Why regular expression so hard?!

If you are looking to only match the numbers on the end of each line use the regex /(\d+)$/. The $ will anchor it to the end of the line for you... So getting all the numbers at the ends of the lines would be
my @numbers; while ( <FILE> ) { /(\d+)$/; push @numbers, $1; }
Update: oops... As merlyn points out, don't do this.

Replies are listed 'Best First'.
RE: RE: RE: Re: Why regular expression so hard?!
by merlyn (Sage) on Aug 31, 2000 at 20:15 UTC
    Oooh. I flagged this kind of stuff as "scary code" already before in the Monastery, I think.

    The rule is "NEVER look at $1 unless it's conditionally based upon a successful match".

    For your code, you might accidentally push the same value two or more times, since your push doesn't depend on the success of the match, so you'll end up grabbing the $1 of the prior match.

    You probably intended something like this:

    my @numbers; while (<FILE>) { push @numbers, $1 if /(\d+)$/; }

    Another way to write that without using a push might be:

    my @numbers = map /(\d+)$/, <FILE>;
    which works because if the match fails on a line, you get an empty list (not a prior $1).

    -- Randal L. Schwartz, Perl hacker