#!/usr/bin/perl -l use strict; use warnings; my %replace = qw/pre 1 prefix 2/; my $norev = '('.join('|', sort keys %replace).')'; my $withrev = '('.join('|', reverse sort keys %replace).')'; while () { chomp; print "Line: $_"; print "norev <$1>" if /$norev/; print "w/rev <$1>" if /$withrev/; } __END__ This line contains prefix (which also matches 'pre')