I am trying to replace every occurrence of “EXECUTE func-name” with “# EXECUTE func-name. followed by a hash value” ONLY if the func-name exists. My regex below doesn’t seem to agree with me.
s/EXECUTE ([\w-]+)\.?/"# EXECUTE $1.\n" . $hash{$1}/eg if (exists($hash{$1}));
Please advise.
Well your code executes the
if-condition before the actual regex, so you probably get a warning when executing your code.When using the
e-modifier you can use perl-code in the “replacement-part” directly:I have added /x, so you can format the regexp to make it actually readable – but now you have to match the whitespace explicitly (that’s why I’ve added
\s+betweenEXECUTEand the group). The$&represents the whole match (so if there is no hash-entry for$1, nothing is changed).That said, using
$&slows down every match and substitution without captures in your entire program. Here’s an improvement: