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

Is there any way to optimize this Percentage validation
$data = 99.9660; if(!($data == 100 || $data =~ /^\d{0,2}(\.\d{0,2})?$/)) { print "Invalid"; }
This should not allow more than 100 and only two decimal places allowed.

Replies are listed 'Best First'.
Re: Optimize Percentage validation
by BrowserUk (Patriarch) on Feb 11, 2005 at 07:10 UTC

    The first rule of optimisation is "Make it work first". Your regex does not even compile, the closing '/' being missing.

    Once you have fixed that, it still will exlude 9, 10, 99 etc. and allow 99.999, 99.9999 etc.

    Once you made the grouping conditional, and anchored the end of the regex, it will probably work, and you could probably save a few microseconds by making the grouping non-capturing.

    But really--how many times are you going to run this test that you need to optimise it?

    Which then makes me wonder what question you are really asking?

    1. Is it, "How can I write a condition to 'not allow more than 100 and only two decimal places'"?
    2. Or maybe, "How can I combine the two parts of this conditional into one"?

    If the former, ask that question--and forget the "optimize" imperative.

    If the latter, it is certainly possible, but it would probably run more slowly that the two-part test.


    Examine what is said, not who speaks.
    Silence betokens consent.
    Love the truth but pardon error.
Re: Optimize Percentage validation
by RazorbladeBidet (Friar) on Feb 11, 2005 at 14:12 UTC
    The code becomes more complex in the cases I tried and you don't gain much (±5% using Benchmark).

    I tried a variation using substr to check the decimal place length and split after checking that the number was between 0 and 100.

    It just makes it unecessarily complicated, and the code runs very quickly as it is.