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; }