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

i am having a file in which i have to substitute certain words with certain value. i store all d words & its value in a hash.

now my problem how to search for that given word & how to replace it using Hash.

i am new with hash i think hash wud be good choice for the given task rather then using arrays.

  • Comment on how to substiute given key with value by using hash.

Replies are listed 'Best First'.
Re: how to substiute given key with value by using hash.
by roboticus (Chancellor) on Jul 13, 2011 at 11:55 UTC

    harshmane:

    I frequently use things like this:

    $ cat t.pl #!/usr/bin/perl use strict; use warnings; use feature ':5.10'; my %Variables = ( NAME=>'Roboticus', STATE=>'KY', BIRD=>'Cardinal' ); my $Template = '{NAME} lives in {STATE}. {FOO}.'; for my $t ($Template=~m/{([A-Z]+)}/g) { $Template =~ s/{$t}/$Variables{$t}/g if exists $Variables{$t}; } say $Template; $ perl t.pl Roboticus lives in KY. {FOO}.

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

      Why not something like:

      >perl -wMstrict -le "my %Variables = ( NAME => 'Roboticus', STATE => 'KY', BIRD => 'Cardinal', ); my $vkey = qr{ @{[ join '|', map quotemeta, keys %Variables ]} }xms; ;; my $Template = '{NAME} lives in {STATE}. {FOO}.'; ;; $Template =~ s{ {($vkey)} }{$Variables{$1}}xmsg; print qq{'$Template'}; " 'Roboticus lives in KY. {FOO}.'
Re: how to substiute given key with value by using hash.
by happy.barney (Friar) on Jul 13, 2011 at 08:43 UTC
    my %hash = (...); my $src = do { local $/; <> }; my $res = join '', map $hash{$_} // $_, split /\b/, $src; # %hash = (a => 'xxx') # $src = 'a b ab'; # $res = 'xxx b ab';
    A reply falls below the community's threshold of quality. You may see it by logging in.