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

Hello, I am beginer in this field. I need help. I tried to write pattern for the range numbers between 1 to 10 . My code looks like this:
#!/usr/bin/perl #$x=11; #$x=0; $x=2; #pattern for range from 1 to 10; if ($x=~ m/[1-9]|10/) { print "Correct match"; } else { print "incorrect"; }
If I assign variable $x=11 it still show me that I have correct match. Any kind of help I will realy appreciate. Vana

Edit kudra, 2002-06-08 Changed title

Replies are listed 'Best First'.
Re: regular expression
by gav^ (Curate) on Jun 08, 2002 at 03:25 UTC
    If it's a number, treat it like one:
    if ($x >= 1 && $x <= 10) { print "Correct match"; } else { print "Incorrect"; }
    I'm not sure why you'd want to write a regular expression for this, unless it was homework :) If you insist, something like this would do the trick:
    if ($x =~ /^([1-9]|10)$/) { # etc }
    This uses ^ and $ to anchor the expression to the whole string and the brackets to restrict the alternation. See perlre for more help.

    gav^

      Thank you ...I am going to see that link. vana
Re: regular expression to match numbers
by Molt (Chaplain) on Jun 08, 2002 at 21:36 UTC

    The reason you're getting a match is that the number '1' is there, it's sitting right at the start of your string- closely followed by another '1' which the regular expression doesn't care about. It just sees that first '1' and stops, not bothering to look ahead.

    If you really do need to throw regexps at this (For example the number is embedded in the string 'I have 10 hamsters') then you need to look at restricting it.

    The following regular expression matches the following.. either start of line or something that isn't a digit, followed by the number you're after, finally followed either by something else that isn't a digit or the end of the line. It will also store the number it found in $1 (Note the use of (?: ... ) to allow me to use non-capturing brackets).

    #!/usr/bin/perl -w use strict; my @tests = ( 'I have 4 hamsters', '10', '11', 'I have 23 camels', 'Where is my wallaby?', '0', '1 1', ); foreach my $test (@tests) { if ($test =~ /(?:\D|^)([1-9]|10)(?:\D|$)/) { print "'$test' matches with the number $1\n"; } else { print "'$test' does not match\n"; } }

    The moral of this story: Regexp's will do exactly what you tell them to do, not what you want them to do. Be careful to check you're capturing in the correct context. I'd recommend the O'Reilly book 'Mastering Regular Expressions' if you're going to be doing a lot of this stuff.