in reply to RE: RE: Re: Why regular expression so hard?!
in thread Why regular expression so hard?!
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:
which works because if the match fails on a line, you get an empty list (not a prior $1).my @numbers = map /(\d+)$/, <FILE>;
-- Randal L. Schwartz, Perl hacker
|
|---|