更简洁的方法来设置perl6中的正则表达式的默认值

p6s*_*eve 6 perl6

要将例如mins-2拆分为单位名称和顺序的组成部分,这就是我想要的

sub split-order ( $string ) {
    my Str $i-s = '1';
    $string ~~ / ( <-[\-\d]>+ ) ( \-?\d? ) /;
    $i-s = "$1" if $1 ne '';
    return( "$0", +"$i-s".Int );
}
Run Code Online (Sandbox Code Playgroud)

似乎perl6应该能够将其打包成更加简洁的措辞.我需要默认顺序为1,其中没有尾随数字.

我可能有点懒,不与行结尾匹配$.试图避免返回Nil,因为这对调用者没用.

任何有更好转变的人?

mor*_*itz 6

用好老了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)
Run Code Online (Sandbox Code Playgroud)


Chr*_*oph 5

这不会完全重现您的算法(特别是不产生负数),但我怀疑它更接近您实际想要实现的目标:

sub split-order($_) {
    /^ (.*?) [\-(\d+)]? $/;
    (~$0, +($1 // 1));
}
Run Code Online (Sandbox Code Playgroud)