Skip to content

Instantly share code, notes, and snippets.

@haukex
Last active August 1, 2018 16:01
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 haukex/c0f06c3d11728a89a6a89f879ea32405 to your computer and use it in GitHub Desktop.
Save haukex/c0f06c3d11728a89a6a89f879ea32405 to your computer and use it in GitHub Desktop.
use warnings;
use 5.018;
# run this multiple times: sometimes it prints "x1x2x1x", sometimes "x2bar-x2x2bar-x"
{
my %repl = ( '-foo-bar-'=>1, '-foo-'=>2 );
my $re = join '|', map { "\\b$_\\b" } keys %repl;
$re = qr/$re/;
say "x-foo-bar-x-foo-x-foo-bar-x"=~s/($re)/$repl{$1}/gr;
}
# and this: sometimes "1 2 1", sometimes "2 bar 2 2 bar"
{
my %repl = ( 'foo bar'=>1, 'foo'=>2 );
my $re = join '|', map { "(?<!\\S)$_(?!\\S)" } keys %repl;
$re = qr/$re/;
say "foo bar foo foo bar"=~s/($re)/$repl{$1}/gr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment