Solved

perl, advanced text substitution

Posted on 2011-03-23
5
453 Views
Last Modified: 2012-06-21
%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";
0
Comment
Question by:rgbcof
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
5 Comments
 
LVL 26

Accepted Solution

by:
wilcoxon earned 500 total points
ID: 35202467
foreach my $key (keys %hash) {
    $string =~ s{$key}{$hash{$key}}g;
}
0
 

Author Closing Comment

by:rgbcof
ID: 35202490
That works.  Awesome.
0
 
LVL 31

Expert Comment

by:farzanj
ID: 35202528
print "First $hash{'YEAR_95'}, then $hash{'YEAR_97'}, then $hash{'YEAR_99'}\n";
0
 
LVL 84

Expert Comment

by:ozo
ID: 35202883
$string=~/(YEAR_\d\d)/$hash{$1}/g;
0
 
LVL 84

Expert Comment

by:ozo
ID: 35202888
$string=~s/(YEAR_\d\d)/$hash{$1}/g;
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I've just discovered very important differences between Windows an Unix formats in Perl,at least 5.xx.. MOST IMPORTANT: Use Unix file format while saving Your script. otherwise it will have ^M s or smth likely weird in the EOL, Then DO NOT use m…
On Microsoft Windows, if  when you click or type the name of a .pl file, you get an error "is not recognized as an internal or external command, operable program or batch file", then this means you do not have the .pl file extension associated with …
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Six Sigma Control Plans

688 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question