perl, advanced text substitution

%hash = (YEAR_95 => '1st daughter', YEAR_97 => '2nd daughter', YEAR_99 => '1st son');
$string = "First YEAR_95, then YEAR_97,  then YEAR_99";

How to substitute pattern YEAR_nn in the string with the hash value?  
So that the result is:  "First 1st daughter, then 2nd daughter,  then 1st son";
rgbcofAsked:
Who is Participating?
 
wilcoxonConnect With a Mentor Commented:
foreach my $key (keys %hash) {
    $string =~ s{$key}{$hash{$key}}g;
}
0
 
rgbcofAuthor Commented:
That works.  Awesome.
0
 
farzanjCommented:
print "First $hash{'YEAR_95'}, then $hash{'YEAR_97'}, then $hash{'YEAR_99'}\n";
0
 
ozoCommented:
$string=~/(YEAR_\d\d)/$hash{$1}/g;
0
 
ozoCommented:
$string=~s/(YEAR_\d\d)/$hash{$1}/g;
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.