#!/usr/bin/perl my %variables = ('$x' => 1); my $test = '$x $y'; $test =~ s/(\$\w+)/exists $variables{$1} ? $variables{$1} : $1/e; print $test, "\n"; __END__ 1 $y