# Use a regex object so it's compiled only once $exp = qr|^DMSC0022\s+\S+\s+(\w+)$|; # Use a non-interpolating string (or escape the $1 as \$1 $str = 'Logfile_Connection_Lost Hostname: $1'; # I can only assume you are assigning to $_ # because this is a snippet from some larger code. On it's # own this is really weird. Normal code would do something # like "DMS ..." =~ $exp instead. $_ = "DMSC0022 X10 oswald"; # Force $exp to execute (don't just eval it, this is more correct) if ( $_ =~ $exp ) { # the eval() is still needed to force the source code # to generate. This is still silly. eval "print \"$str\""; }