Solved

perl, advanced text substitution

Posted on 2011-03-23
5
443 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
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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

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…
There are many situations when we need to display the data in sorted order. For example: Student details by name or by rank or by total marks etc. If you are working on data driven based projects then you will use sorting techniques very frequently.…
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…

828 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