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