The trick is to think of sequences of digits, not the number they represent. What options exist for the first digit encountered? What conditions have to be met after a certain one of them?
use strict;
use Test::More 'no_plan';
my $rx = qr/\A
(?: [0-4]\d? | 5?[0-5] ) \.
(?: [0-4]\d? | 5?[0-5] )
\z/x;
my %test = (
'56.0' => 0,
'0.56' => 0,
'48.56' => 0,
'56.10' => 0,
'55.0' => 1,
'55.55' => 1,
'0.0' => 1,
'10.10' => 1,
);
my $result;
is(/$rx/, !!$result, $_) while ($_, $result) = each %test;
__END__
ok 1 - 0.56
ok 2 - 56.10
ok 3 - 55.0
ok 4 - 55.55
ok 5 - 48.56
ok 6 - 56.0
ok 7 - 10.10
ok 8 - 0.0
1..8
If the first digit seen is any of 0 to 4, then it is legal, and may optionally be followed by any other digit. If it is 5, it is legal, and may optionally be followed by another digit from the 0-5 range. Any other sequence is illegal.
Update: I knew I was missing something when I wrote my test cases.. sigh. And it is so obvious. So there's a third case if the first digit is 6-9: it it is legal if not followed by anything.
my $rx = qr/\A
(?: [0-4]\d? | 5?[0-5] | [6-9] ) \.
(?: [0-4]\d? | 5?[0-5] | [6-9] )
\z/x;
Adding some cases to the test:
'62.6' => 0,
'9.97' => 0,
'55.9' => 1,
'1.49' => 1,
'6.7' => 1,
'06.7' => 1,
They all pass. Now let's hope I'm not still a bonehead.
Makeshifts last the longest.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.