in reply to complex string matching

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 $_; } }

Replies are listed 'Best First'.
Re^2: complex string matching
by freebsdboy (Novice) on Nov 04, 2010 at 12:42 UTC
    Thanks - it seems that it would be best to split the strings into key value pairs, so that: makes comparison easier to deal with non exact matches, keys that may have a different value and thus would have been seen as a different key all together. Yea realize the found not found issue - was trying to get the foundational compare to work properly. I had tried the m/$string/ type of comparison earlier but that didn't work, tried the hash compare but didn't realize its limits. Good to see the escape regexp option too.