On Aug 17, David T-G said:
> my $string = "Hello, #NAME_FIRST# #NAME_LAST# from #STATE#!" ;
>
>and I want to replace those chunks each with another string, what is a
>good way to approach that? I'd love to use something like
>
> my %xlate =
> (
> NAME_FIRST => "David",
> NAME_LAST => "T-G",
> STATE => "confusion"
> ) ;
>
>that I can load up for each record and then just throw it at the master
>string and get a custom version out, but I don't see how to do that. For
>instance, in php, I would write something like
>
> $fields = array('#NAME_FIRST#','#NAME_LAST#','#STATE#') ;
> $values = array('David','T-G','confusion') ;
> $custom = preg_replace($fields,$values,$string) ;
>
>and be done.
That's good of you to show how you'd do it in another language (yes, even
if that language is PHP ;) ), because it clears up what you want to do.
There are two ways I see of doing it:
$string =~ s{#(.*?)#}{
if (exists $xlate{$1}) { $xlate{$1} } # if it's a valid key
else { "#$1" } # if it's not in the hash, don't touch it
}ge;
The other way builds a regex of the keys in the hash first:
my $keys = join '|', map quotemeta, keys %xlate;
# quotemeta() make's sure any regex-characters in the keys are escaped
$string =~ s/#($keys)#/$xlate{$1}/g;
You'll notice for the second code we didn't need the 'e' modifier. That's
because in the first chunk of code, the replacement was a function -- that
is, it wasn't just a string, it was code that needed to be executed. The
second time, though, we know $1 is a valid key in the hash, so there are
no precautions needed.
--
Jeff "japhy" Pinyan [EMAIL PROTECTED] http://www.pobox.com/~japhy/
RPI Acacia brother #734 http://www.perlmonks.org/ http://www.cpan.org/
<stu> what does y/// stand for? <tenderpuss> why, yansliterate of course.
[ I'm looking for programming work. If you like my work, let me know. ]
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]