Skip to content

Instantly share code, notes, and snippets.

@Xliff
Created January 22, 2020 03:06
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 Xliff/e1a0e93da6c067b0873a9a215378e8ea to your computer and use it in GitHub Desktop.
Save Xliff/e1a0e93da6c067b0873a9a215378e8ea to your computer and use it in GitHub Desktop.
String Splitting

Yes, I know it's not as idiomatic as it could be, but....

sub string-split($str, +@pos) {
    my ($str-a, $str-b);
    my ($r, $idx) = ($str, 0);

    gather while @pos || $str-a {
        unless +@pos {
          take $r;
          last;
        }

        my $a = @pos.shift - $idx if +@pos;

        $str-a = $r.substr(0, $a);
        $str-b = $r.substr($a, *);
        take $str-a;
        ($r, $idx) = ($str-b, $a);
    }
}

"aaabbcccc".&string-split(3, 5).say
@Xliff
Copy link
Author

Xliff commented Jan 22, 2020

Ah! $str-b is uesless, so...

sub string-split($str, +@pos) {
    my $str-a;
    my ($r, $idx) = ($str, 0);

    gather while @pos || $str-a {
        unless +@pos {
          take $r;
          last;
        }

        my $a = @pos.shift - $idx if +@pos;

        $str-a = $r.substr(0, $a);
        $r     = $r.substr($idx = $a, *);
        take $str-a;
    }
}

"aaabbcccc".&string-split(3, 5).say

@holli-holzer
Copy link

The point is, this should be a core operation. When "split on" is a thing, "split at" should be too. Even though CSV is more common these days than fixed lenght formats.

.say for split-at( "aaabccccdd", (3, 4, 8) );

sub split-at( $s is copy, @positions )
{
  my $done = 0;

  gather {
    for @positions -> $p
    {
      take $s.substr($done, $p - $done );
      $done = $p;
    }
    take $s.substr( $done, * );
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment