PhosphoricX has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to perform a subsitution if an entry exists in my hash:

s/(\$\w+)/$variables{$1}/g if(exists $variables{$1};

How can I assure that a match, not found in my hash will not be replaced?

Replies are listed 'Best First'.
Re: Substitutions if hash entry exists
by Tomte (Priest) on Mar 19, 2004 at 10:32 UTC
    Use the e-modifier:
    #!/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

    Update: Every possible value is substituted (albeit by itself, if not existing as hash-key), if this is too much or discomforting, just split match and substitution...

    regards,
    tomte


    Hlade's Law:

    If you have a difficult task, give it to a lazy person --
    they will find an easier way to do it.

Re: Substitutions if hash entry exists
by bart (Canon) on Mar 19, 2004 at 10:34 UTC
    You have to make the RHS executable, by adding a /e modifier, and do the check there. I think this will do for your case:
    s/(\$\w+)/exists $variables{$1} ? $variables{$1} : $1/ge;
    but personally, I'd remove the '$' from the hash keys, and go for
    s/(\$(\w+))/exists $variables{$2} ? $variables{$2} : $1/ge;
Re: Substitutions if hash entry exists
by PhosphoricX (Sexton) on Mar 19, 2004 at 11:16 UTC
    Thanks a lot guys, using /e I was able to solve the problem.