Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: String replace with function

by GrandFather (Sage)
on Sep 19, 2016 at 21:12 UTC ( #1172181=note: print w/replies, xml ) Need Help??


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!

Premature optimization is the root of all job security

Replies are listed 'Best First'.
Re^2: String replace with function
by shmem (Chancellor) on Sep 19, 2016 at 21:33 UTC
    Also, you don't need & to call a function, and in fact should (almost) never use that call syntax.

    To expand this bit, &function was the perl4 way to invoke subroutines. In perl5, &function

    • passes the current @_ to the invoked subroutine
    • overrides function prototypes

    Function prototypes? You should (almost) never use that... see perlsub.

    perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'
Re^2: String replace with function
by AnomalousMonk (Chancellor) on Sep 19, 2016 at 23:08 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1172181]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2018-07-20 09:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?















    Results (427 votes). Check out past polls.

    Notices?