in reply to seaching for replacement
I wondered how you might cope with dictionary words with a space in them, like "bar graph". The solution I came up with was to do a descending lexical sort of the dictionary keys when constructing the regex. That way "bar graph" will be matched in preference to "bar" and "graph" will already have been consumed by the regex if preceded by "bar". This code
use strict; use warnings; use Data::Dumper; open my $dictFH, q{<}, \ <<'DICT' or die qq{open: < HEREDOC: $!\n}; 1 eat 2 habit 3 boy 4 man-kind 5 man 6 kind 7 bar 8 graph 9 bar graph DICT my %dict = reverse map { split m{\s+}, $_, 2 } map { chomp; $_ } <$dictFH>; close $dictFH or die qq{close: < HEREDOC: $!\n}; print Data::Dumper->Dumpxs( [ \ %dict ], [ qw{ *dict } ] ); my $text = <<'TEXT'; The boy has a habit of eating kind of like a man. Man-kind, as a group, does not wear habits. Kind of you to watch what you eat. Make a bar graph of what drinks are drunk in a bar and the graph could be coloured in. TEXT my $rxDict = do { local $" = q{|}; qr {(?xi) \b( @{ [ map quotemeta, sort { $b cmp $a } keys %dict ] } )\b } }; $text =~ s{$rxDict}{ $dict{ lc $1 } }eg; print $text;
produces
%dict = ( 'eat' => '1', 'man' => '5', 'kind' => '6', 'bar' => '7', 'man-kind' => '4', 'bar graph' => '9', 'boy' => '3', 'graph' => '8', 'habit' => '2' ); 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. Make a 9 of what drinks are drunk in a 7 and the 8 could be coloured in.
I hope this is of interest.
Cheers,
JohnGG
Update: Sorting the keys in ascending lexical order shows what happens when the shorter is chosen before the longer. The transformed text becomes
The 3 has a 2 of eating 6 of like a 5. 5-6, as a group, does not wear habits. 6 of you to watch what you 1. Make a 7 8 of what drinks are drunk in a 7 and the 8 could be coloured in.
|
|---|