%d = ( foo => sub { "[@_]"; }, bar => sub { "(@_)"; }, ); $_ = 'foo fooz bar baz1'; s/(\w+)(?(?{ !$d{$1} })(?!))/$d{$1}->($1)/ge; print "$_\n";