in reply to how to substiute given key with value by using hash.

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.

Replies are listed 'Best First'.
Re^2: how to substiute given key with value by using hash.
by AnomalousMonk (Archbishop) on Jul 13, 2011 at 19:54 UTC

    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}.'