in reply to String replace with function
Use the /e switch (see the end of the Modifiers section in perlre):
use strict; use warnings; my $str = "1 2 345 23"; $str =~ s/(\d+)/add($1)/ge; print $str; sub add { my ($num) = @_; return $num + 10; }
Prints:
11 12 355 33
Note that your sample was missing 's' in front of the first / that denotes substitution instead of match and was missing capture parenthesis in the match. Also, you don't need & to call a function, and in fact should (almost) never use that call syntax.
Oh, and a sub called 'add' should add, not multiply. If you can't get simple names like that right you are going to cause a lot of grief for someone down the road!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: String replace with function
by shmem (Chancellor) on Sep 19, 2016 at 21:33 UTC | |
|
Re^2: String replace with function
by AnomalousMonk (Archbishop) on Sep 19, 2016 at 23:08 UTC |