Created
July 23, 2013 09:17
-
-
Save hoelzro/6061095 to your computer and use it in GitHub Desktop.
Example of weird behavior when using regexes in a class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use v6; | |
sub parse(Str $time-spec) returns Int { | |
my regex hours { | |
$<value>=(\d+)h | |
} | |
my regex minutes { | |
$<value>=(\d+)m | |
} | |
my regex seconds { | |
$<value>=(\d+)s | |
} | |
my regex timespec { | |
<hours>? | |
<minutes>? | |
<seconds>? | |
} | |
if $time-spec ~~ /^<timespec>$/ { | |
my ( $hours, $minutes, $seconds ) = map({ | |
my $value = $<timespec>{$_}[0]<value>; | |
$value ~~ Match ?? $value.Int !! 0 | |
}, <hours minutes seconds>); | |
return ($hours * 3_600) + ($minutes * 60) + $seconds; | |
} else { | |
die 'Failed to parse timespec!'; | |
} | |
} | |
class Timer { | |
method parse(Str $time-spec) returns Int { | |
my regex hours { | |
$<value>=(\d+)h | |
} | |
my regex minutes { | |
$<value>=(\d+)m | |
} | |
my regex seconds { | |
$<value>=(\d+)s | |
} | |
my regex timespec { | |
<hours>? | |
<minutes>? | |
<seconds>? | |
} | |
if $time-spec ~~ /^<timespec>$/ { | |
my ( $hours, $minutes, $seconds ) = map({ | |
my $value = $<timespec>{$_}[0]<value>; | |
$value ~~ Match ?? $value.Int !! 0 | |
}, <hours minutes seconds>); | |
return ($hours * 3_600) + ($minutes * 60) + $seconds; | |
} else { | |
die 'Failed to parse timespec!'; | |
} | |
} | |
} | |
say parse('10s'); # this works fine | |
say Timer.parse('10s'); # this fails with the following error: | |
#`( | |
Nominal type check failed for parameter ''; expected Timer but got Cursor instead | |
in regex timespec at test.p6:42 | |
in method INTERPOLATE at src/gen/CORE.setting:10701 | |
in regex at test.p6:48 | |
in method ACCEPTS at src/gen/CORE.setting:10800 | |
in method parse at test.p6:48 | |
in block at test.p6:62 | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment