Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

perl, advanced text substitution

Posted on 2011-03-23
5
Medium Priority
?
457 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 27

Accepted Solution

by:
wilcoxon earned 2000 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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

Email validation in proper way is  very important validation required in any web pages. This code is self explainable except that Regular Expression which I used for pattern matching. I originally published as a thread on my website : http://www…
Checking the Alert Log in AWS RDS Oracle can be a pain through their user interface.  I made a script to download the Alert Log, look for errors, and email me the trace files.  In this article I'll describe what I did and share my script.
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