I want to pass an entire s/foo/bar/i regexp substitution into a method as a (preferrable single) parameter.
Can that be done?
No, I don't think so. In your place, I'd pass two things: a qr// regexp, and a code ref for the substitution part.
sub foo {
my($qr, $replace) = @_;
s/$qr/$replace->()/ge;
}
$_ = "This is a new dawn.";
foo(qr/(\w+)/, sub { ucfirst $1 });
print;
This makes use of the fact that $1 etc. are (
localized) global variables.
Alternatively, pass just a code ref for the whole s/// statement, as a callback. This callback can do more than just a substitution, though.
sub bar {
my $callback = shift;
$callback->();
}
bar(sub { s/(\w+)/\u$1/g; });
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.