To split e.g. mins-2 into component parts of units name and order, this does what I want
sub split-order ( $string ) {
my Str $i-s = '1';
$string ~~ / ( <-[\-\d]>+ ) ( \-?\d? ) /;
$i-s = "$1" if $1 ne '';
return( "$0", +"$i-s".Int );
}
It seems that perl6 should be able to pack this into a much more concise phrasing. I need default order of 1 where there is no trailing number.
I am probably being a bit lazy not matching the line end with $. Trying to avoid returning Nil as that is not useful to caller.
Anyone with a better turn of phrase?
How about using good old split
?
use v6;
sub split-order(Str:D $in) {
my ($name, $qty) = $in.split(/ '-' || <?before \d>/, 2);
return ($name, +($qty || 1));
}
say split-order('mins-2'); # (mins 2)
say split-order('foo42'); # (foo 42)
say split-order('bar'); # (bar 1)
This does not reproduce your algorithm exactly (and in particular doesn't produce negative numbers), but I suspect it's closer to what you actually want to achieve:
sub split-order($_) {
/^ (.*?) [\-(\d+)]? $/;
(~$0, +($1 // 1));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With