http://www.perlmonks.org?node_id=157389


in reply to Detect presence of numbers 1-9

This looks like a task for a regex:

if ( $scalar =~ /^[12345]+$/ ) { print "match"; } else { print "no match"; }

Update: as crazyinsomniac pointed out you can also write:

if ( $scalar !~ /[^12345]/ ) { print "match"; }

alex pleiner <alex@zeitform.de>
zeitform Internet Dienste

Replies are listed 'Best First'.
Re: Re: Detect presence of numbers 1-9
by demerphq (Chancellor) on Apr 08, 2002 at 10:17 UTC
    if ( $scalar !~ /[^12345]/ ) { print "match"; }

    Hmm, that double negative sure is confusing. Maybe simplifying it would be a little clearer (I know regexes pretty well and I had to think about this for a second...)

    if ( $scalar =~ /[^12345]/ ) { print "Illegal parameter: $scalar"; } else { print "Acceptable parameter: $scalar"; }
    Maybe some would disagree but to me I like to say my regexes out loud to understand them and I find

    if it matches any character that isn't a 1-5 then it is bad

    much easier (read faster) to understand than

    if it does not match any character that is not a 1-5 then it is good.

    I agree im probably being a bit pedantic but I think you can see what I mean...

    Yves / DeMerphq
    ---
    Writing a good benchmark isnt as easy as it might look.

Re: Re: Detect presence of numbers 1-9
by Dog and Pony (Priest) on Apr 08, 2002 at 09:20 UTC
    If you do have a sequence like that, you can make it look even cleaner by writing it:
    $scalar =~ /^[1-5]+$/
    or
    $scalar !~ /[^1-5]/

    You have moved into a dark place.
    It is pitch black. You are likely to be eaten by a grue.
      I'd avoid the double-negative tests because they would match the empty string (and undef, but you do have warnings enabled, right?). In most cases, it's usually better to state what you want, not what you don't want. :-)

      ------
      We are the carpenters and bricklayers of the Information Age.

      Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

Re: Re: Detect presence of numbers 1-9
by Juerd (Abbot) on Apr 08, 2002 at 09:37 UTC

    if ( $scalar =~ /^[12345]+$/ ) {

    Please note that $ also matches before a trailing \n character, and that this regex also matches "111\n". But I'd go for the negative match anyway, because it seems more natural to me.

    U28geW91IGNhbiBhbGwgcm90MTMgY
    W5kIHBhY2soKS4gQnV0IGRvIHlvdS
    ByZWNvZ25pc2UgQmFzZTY0IHdoZW4
    geW91IHNlZSBpdD8gIC0tIEp1ZXJk
    

Re: Re: Detect presence of numbers 1-9
by tachyon (Chancellor) on Apr 08, 2002 at 09:57 UTC
    # or even: $scalar =~ /[^1-5]/ ? &is_bad : &is_good; print $scalar =~ /[^1-5]/ ? "bad" : "OK!"; $scalar !~ /[^1-5]/ && print "OK!"; print "OK!" unless $scalar =~ /[^1-5]/; print "OK!" if $scalar !~ /[^1-5]/;

    STATMWTDI cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print