Last active
August 1, 2018 16:01
-
-
Save haukex/c0f06c3d11728a89a6a89f879ea32405 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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