Skip to content

Instantly share code, notes, and snippets.

@gerdr
Created May 30, 2012 17:11
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 gerdr/2837706 to your computer and use it in GitHub Desktop.
Save gerdr/2837706 to your computer and use it in GitHub Desktop.
regex-dna failure golf
use v6;
sub my-subst($self, $matcher, $replacement,
:ii(:$samecase), :ss(:$samespace),
:$SET_CALLER_DOLLAR_SLASH, *%options) {
my $matches := $self.match($matcher, |%options);
return $self unless $matches;
if $matches ~~ Match {
$matches := ($matches,).list;
}
else {
$matches := $matches.list;
}
my $caller_dollar_slash := pir::find_caller_lex__Ps('$/');
my $prev = 0;
my $result = '';
my $i = 0;
while $matches {
say ++$i;
my $m = $matches.shift;
$result ~= $self.substr($prev, $m.from - $prev);
$caller_dollar_slash = $m if $SET_CALLER_DOLLAR_SLASH;
my $real_replacement = ~($replacement ~~ Callable ?? $replacement($m) !! $replacement);
$real_replacement = $real_replacement.samecase(~$m) if $samecase;
$real_replacement = $real_replacement.samespace(~$m) if $samespace;
$result ~= $real_replacement;
$prev = $m.to;
}
$result ~= $self.substr($prev);
$result;
}
my $string = 'abc' x 10000;
my %hash = :a(1), :b(2), :c(3);
$string = my-subst($string, /(<[abc]>)/, -> $/ { %hash{$0} }, :global);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment