Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks, this script accepts two numbers and prints the range. When I allow a negative for the first number it works:
#!/usr/bin/perl while (<>) { print if m!(^-{0,1}\d*)\s+(\d*)!m; print "$_\n" for ($1 .. $2); } But when I allow both to be negative it doesn't: #!/usr/bin/perl while (<>) { print if m!(^-{0,1}\d*)\s+(^-{0,1}\d*)!m; print "$_\n" for ($1 .. $2); }
Could a blessed monk point out my folly please? Thanks for all the replies to my previous question (esp. dws) and TIA for this one. Jono

Replies are listed 'Best First'.
Re: regex negative numbers
by bjelli (Pilgrim) on Aug 28, 2002 at 08:13 UTC

    To summarize: the problem is in the pattern, (or in the fact that you didn't check if the pattern mached at all).

    I've changed three things about the pattern:

    1. ? instead of {0,1}
    2. ^ just once
    3. \d+ instead of \d*
    4. discarded the /m at the end
    while (<DATA>) { chomp; print "Test case '$_'\n"; if ( m!^(-?\d+)\s+(-?\d+)! ) { print "$_, " for ($1 .. $2); } else { print "doesn't match"; } print "\n\n"; } __DATA__ 1 6 -4 6 -4 -1 6 1 6 -4 -1 -4

    making the program count *backwards* is left as an exercise to the reader.

    --
    Brigitte    'I never met a chocolate I didnt like'    Jellinek
    http://www.horus.com/~bjelli/         http://perlwelt.horus.at
Re: regex negative numbers
by theorbtwo (Prior) on Aug 28, 2002 at 06:50 UTC

    You didn't watch what you were doing when you copy-and-pasted. Your second regex contains two ^ assertations... in other words, you required the string to begin two sepperate places. (There are circumstances where it is kosher to have two ^s in a regex -- to whit, where there can be nothing between them, or where one is optional. Oh, or if you use the approprate modifer (/m, IIRC, but my memory is bad), ^ will match after a newline as well as at the begnning of the string). Read perlre for more info on regexes.


    Confession: It does an Immortal Body good.

Re: regex negative numbers
by hotshot (Prior) on Aug 28, 2002 at 06:37 UTC
    first, you can use '?' instead of '{0,1}'. secondly, that works for me (I'v check this):
    while (<>) { print if /^(-?\d+)\s+(-?\d+)/; print $_ for ($1..$2); }


    , Hotshot
Re: regex negative numbers
by Django (Pilgrim) on Aug 28, 2002 at 06:51 UTC
    What you're probably trying to do is this:
    while (<>) { / ( ^ -? \d+ ) \s+ # optional minus at start of line, some digits, some space ( -? \d+ ) # same thing, but NOT at start of line /x # eXplanation mode (m is useless when you read line by line) and print; # I didn't get the purpose of your print statements - # this one will simply print the line if matched. }