Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

substituting with hash data

by Anonymous Monk
on Aug 16, 2001 at 18:00 UTC ( [id://105377]=perlquestion: print w/replies, xml ) Need Help??

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 - mneylon-pm@masemware.com || "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.

    --
    <http://www.dave.org.uk>

    Perl Training in the UK <http://www.iterative-software.com>

      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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://105377]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (5)
As of 2024-03-29 12:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found