in reply to Why regular expression so hard?!

Put the filename on the command line, then do:
@numbers = map /(\d+)/g, <>;

-- Randal L. Schwartz, Perl hacker

Replies are listed 'Best First'.
RE: Re: Why regular expression so hard?!
by Anonymous Monk on Aug 31, 2000 at 19:56 UTC
    I am sorry. May be I should rephrase my question. These are not the only numbers in file. There are more numbers with each line. I just need to match these one and print. Thanks.
      perl -ne 'if (/(\d+(\.\d+)?)$/) {print $1, "\n"}' file1 file2
      That picks up numbers at the end of the line. If you want the last number in the line (ignoring possible trailing text) throw in \D* before the $.
      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.
        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

      So how do you decide whether a number is to be printed or not? Can you give a rule? Is it based on what it is, or where it is, or where it isn't?

      -- Randal L. Schwartz, Perl hacker