Skip to content

Instantly share code, notes, and snippets.

@haukex
Last active Aug 1, 2018
Embed
What would you like to do?
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