6

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?

librasteve
  • 6,832
  • 8
  • 30

2 Answers2

6

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)
moritz
  • 12,710
  • 1
  • 41
  • 63
5

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));
}
Elizabeth Mattijsen
  • 25,654
  • 3
  • 75
  • 105
Christoph
  • 164,997
  • 36
  • 182
  • 240