foreach my $line (@vcvars) { if ($line =~ /^set INCLUDE=(.*)/) { ## use the ^ and $ anchors whenever possible my @paths = split(/;/, $1); # $1 is the part in brackets in the regex above print VCVARS32 "set INCLUDE="; print VCVARS32 join(";", # concatenate list of strings using semicolons grep( !/^\%SRVBUILD\%/, @paths) # return list of the strings that do not start with %SRVBUILD% ); print VCVARS32 "\n"; next; } # no else{} necessary; next() will prevent you falling through to here # in you "set SRVBUILD" case: # $line =~ s/^\=(\W*)/\=/; # this will not work since you're using an ^ anchor; # the "=" is not at the beginning of the string, is it? # also, \W matches any NONword-character; anything NOT a letter, digit or underscore # but if I understood correctly you want to change everything after the "=" # you can simply use a s///ubstitution here # since if the left side does not match, nothing gets replaced; # no need for an if(){} s/^(set SRVBUILD)=.*/$1=INI_CODE_HERE/; # and then we can just let the boilerplate print handle the modified $line print VCVARS32 $line; }