Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

RE: RE: Re: Why regular expression so hard?!

by Boogman (Scribe)
on Aug 31, 2000 at 20:02 UTC ( [id://30578]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://30578]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2024-03-29 02:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found