If you want to do your replacement in a case insensitive fashion, you can use case insensitive matching (i modifier, see perlretut) and run your matched variation through the lc function. You can also join your keys with an alternator to generate a regular expression that will exactly match only your keys. Something like:
#!/usr/bin/perl use strict; use warnings; my %dict; while ( <DATA> ) { my ( $key, $val ) = /^(\d+)\s+(\S+)/; $dict{ $val } = $key; } my $regex = '\b' . join('\b|\b', map "\Q$_\E", sort {length $b <=> len +gth $a} keys %dict) . '\b'; open my $fh, '<', 'junk.txt' or die "Open failed: $!"; while (defined(my $line = <$fh>)) { $line =~ s/($regex)/$dict{lc($1)}/ieg; print $line; } __DATA__ 1 eat 2 habit 3 boy 4 man-kind 5 man 6 kind
tested with input file junk.txt:
The boy has a habit of eating kind of like a man. Man-kind, as a grou +p, does not wear habits. Kind of you to watch what you eat.
which gives the output:
The 3 has a 2 of eating 6 of like a 5. 4, as a group, does not wear habits. 6 of you to watch what you 1.
Note the use of the quote-meta operators \Q and \E to avoid some nasty corner cases. Also note that your original dictionary read was not reading in man-kind because \w does not match -. I've fixed that by correcting the regular expression and sorting the keys from longest to shortest in the join, so hyphenates are guaranteed to match before any of their sub strings. I've added a defined test to your file read, since as you had it your while-loop would have exited if your input file has a blank line (defined is implicit in the while(<$fh>) construct). I've also changed to a tested, 3-argument open and indirect file handle, all of which are considered Good Things(tm).
In reply to Re: seaching for replacement
by kennethk
in thread seaching for replacement
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |