Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More concise way to setup defaults for regex in perl6

Tags:

raku

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?

like image 641
p6steve Avatar asked Apr 05 '18 21:04

p6steve


2 Answers

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)
like image 98
moritz Avatar answered Sep 19 '22 10:09

moritz


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));
}
like image 29
Christoph Avatar answered Sep 18 '22 10:09

Christoph