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

I need to do simple substitution using the keys and values of a hash table. But I'm new and can't get it to work. I just want the script to check for a "key" in the hash, and replace it with its corresponding "value." Any help??

Replies are listed 'Best First'.
Re: substituting with hash data
by Cirollo (Friar) on Aug 16, 2001 at 18:04 UTC
    Something like this perhaps?
    $string =~ s/$_/$hash{$_}/g for (keys %hash);
Re: substituting with hash data
by Masem (Monsignor) on Aug 16, 2001 at 18:05 UTC
    It should be a simple substitution:
    $a = "this is a test"; %b = ( is => 'was' ); foreach my $key ( keys %b ) { $a =~ s/$key/$b{$key}/g; } print $a,"\n"; # output: thwas was a test

    Dr. Michael K. Neylon - || "You've left the lens cap of your mind on again, Pinky" - The Brain

Re: substituting with hash data
by davorg (Chancellor) on Aug 16, 2001 at 18:06 UTC

    Do you mean something like:

    my $srch = join ('|', map {'\b.'quotemeta($_).'\b'} keys %trans); $text =~ s/($srch)/$trans{$1}/g;

    Looks like you're writing your own templating system. There are plenty of them on CPAN, why not look for one there.


    Perl Training in the UK <>

      Speaking of which... if you're looking to do HTML templating, you might take a look at this nice overview of your options (written by perrin): Choosing a Templating System