pileofrogs has asked for the wisdom of the Perl Monks concerning the following question:
Ahoy, ye salty Monks.
I just had a situation where I wanted to perform a transformation on every instance of a pattern in a string, but that transformation is dynamic, and I don't know how to do that.
For example, say I want to replace every instance of a number with a different form of the same number. Specifically, I want to replace 20000 with 20 K, 20000000 with 20 M, and 12345678 with 12 M.
The first thing I tried was:
sub munge { my $num = shift; if ( $number > 1000000 ) { return ($number / 1000000).' M'; } if ( $number > 1000 ) { return ($number / 1000).' K'; } } my $text = <<END; Hello 200000 how 12345678 are you? I have 35000 dogs. I consume 32000000 hamburgers a day. END $text =~ s/(\d+)/munge($1)/g;
...but that didn't work.
Thanks!
--Pileofrogs
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: substitute with sub result?
by toolic (Bishop) on Mar 07, 2009 at 01:00 UTC | |
by pileofrogs (Priest) on Mar 07, 2009 at 01:03 UTC | |
|
Re: substitute with sub result?
by almut (Canon) on Mar 07, 2009 at 01:02 UTC | |
|
Re: substitute with sub result?
by CountZero (Bishop) on Mar 07, 2009 at 09:09 UTC |