1) You can escape regex special characters with quotemeta or inside a regex with \Q$myliteralstring\E. But that is not neccessary here because you try to match the string via hash comparision
2) Hash comparision is only useful if you can make exact matches, otherwise you need regexes. Make sure you have exactly the line, with spaces and all
3) You try to find out if a config option is NOT in the file and then append it. Obviously you can't know that it isn't in the file until you read and compared ALL lines of the file. Consequently you can't print "not found" and add the line inside the loop that loops through the file. THAT observation is only possible after the loop. A correct while loop would look like this:
my $found=0; while(<USERPREF>) { chomp; if (exists($update_words{$_})) { print "found $_ \n"; $found=1; } } if (not $found) { print "not found $_ \n"; #write }
4) What happens if the option line is already in the file, but with a different value, i.e. user_pref("app.update.auto", true); instead of false ? If the later user_pref line trumps the earlier, you are fine. If it is the other way round, you would need to insert the lines at the beginning of the output file.
If the same option twice would be unwanted or cause of error or warning messages, you can't just compare with a hash, you would need to use regexes to first find the option line (without the option value), then replace the line with the correct option value
Or, if you don't want to use regexes, change your hash to have user_pref("app.update.auto" as key and the complete line as value. In the loop cut away the option value from every line (i.e. my $comparevalue= split(/,/,$_); might do the trick if no ',' is ever in an option name) and compare that with the hash:
while (<$fh>) { chomp; my $comparevalue= split(/,/,$_); $update_words{$comparevalue}= $_; print "$_\n"; } ... while(<USERPREF>) { chomp; my $comparevalue= split(/,/,$_); if (exists($update_words{$comparevalue})) { print "found $_ \n"; $found=1; print OUTFILE $update_words{$comparevalue} } else { print OUTFILE $_; } }
In reply to Re: complex string matching
by jethro
in thread complex string matching
by freebsdboy
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |