#!/usr/bin/perl use strict; use warnings; my %dict; while ( ) { my ( $key, $val ) = /^(\d+)\s+(\S+)/; $dict{ $val } = $key; } my $regex = '\b' . join('\b|\b', map "\Q$_\E", sort {length $b <=> length $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 #### 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. #### 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.