Solved

perl, advanced text substitution

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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Syslog text file into database or into .CSV 19 182
Perl string replace for refred url 9 70
Migrate OTRS to newest version. 1 501
Union rows in array that have common elements 2 110
Many time we need to work with multiple files all together. If its windows system then we can use some GUI based editor to accomplish our task. But what if you are on putty or have only CLI(Command Line Interface) as an option to  edit your files. I…
In the distant past (last year) I hacked together a little toy that would allow a couple of Manager types to query, preview, and extract data from a number of MongoDB instances, to their tool of choice: Excel (http://dilbert.com/strips/comic/2007-08…
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…

733 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