On 8/27/07, Petra Vide Ogrin <[EMAIL PROTECTED]> wrote: > Hi all, > > I have a hash and some prose text and want my perl to identify the keys of > the hash in this text and replace them with the corresponding values of > the keys. > > I tried the following > > foreach (keys %expan) { > if ($sbl =~ m/$_/g) { > $sbl =~ s/$_/$expan{$_}/g; > } > } > > but it doesn't seem to work properly. What am I doing wrong? snip
I don't see anything particularly wrong in your code, but this isn't really a job for a hash. An AoA is better suited to the job. The main reason is that a hash must use a string for a key and your really want to use a pre-compiled regex instead (even if it is only a literal). The speed boost is significant (qr is about twice as fast). I am currently using a system like this to correct pipe delimited files that have pipes in the middle of some fields. Every time a new erroneous field is detected (too many pipes on a line) I add another element to @replace. Of course, you might not want to do this at all if what you are really doing is replacing things like "EMAIL_GOES_HERE", "SUBJECT_HERE", etc. If you are doing things like that then a template engine is a better solution. There are many on CPAN to choose from. #!/usr/bin/perl use strict; use warnings; my @replace = ( #replace with [ qr/foo/, 'Foo' ], [ qr/bar/, 'Bar' ], [ qr/baz/, 'Baz' ] ); my $text = "This is a test of replacements for foo, bar, and baz. The output should have foo looking like Foo, bar looking like Bar, and likewise for baz."; $text =~ s/$_->[0]/$_->[1]/g for @replace; print "$text\n"; -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/