print do_stuff(); #### use strict; use warnings; use 5.012; my $target = 'hello'; my %should_replace = ('hello' => 1); my $repl = 'Hello'; $_ = 'hello world goodbye'; s/$target/print $should_replace{$target} ? "$repl " : "[$repl] "/ex; #### use strict; use warnings; use 5.012; my $text = 'hello world goodbye'; my $target = 'hello'; my %should_replace = ('hello' => undef); my $repl = 'Hello'; if ($text =~ $target) { my $output = exists $should_replace{$target} ? "$repl " : "[$repl] "; say $output; } #### use strict; use warnings; use 5.012; my $text = 'hello world goodbye'; my $target = 'hello'; my %keys = ('world' => undef); my $repl = 'Hello'; if ($text =~ $target) { my $output; if (exists $keys{$target}) { $output = $repl; } else { $output = "[$repl]"; } say "$output "; } --output:-- [Hello]