Skip to content

Instantly share code, notes, and snippets.

@hoelzro
Created July 23, 2013 09:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hoelzro/6061095 to your computer and use it in GitHub Desktop.
Save hoelzro/6061095 to your computer and use it in GitHub Desktop.
Example of weird behavior when using regexes in a class
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