#!/usr/bin/perl -w use strict; my %words = map { $_ => 1 } qw($Word $name); my $line = '$Word $ $foo'; $line =~ s/(\$\w*)/exists $words{$1} ? $1 : qq{ dollar }/eg; print $line;