Is there a way to use a variable as modifier in a substitution?
my $search = 'looking';
my $replace = '"find: $1 ="';
my $modifier = 'ee';
s/$search/$replace/$modifier;
I need to use an array of hashes to make bulk search-replace with different modifiers.
While the method using
eval
to compile a new substitution is probably the most straightforward, you can create a substitution that is more modular:This is only lightly tested, and it is left as an exercise for the reader to implement other flags like
g
You could use
eval
, if you put on your safety goggles and your divide-by-zero suit.E.g.:
Here's a combination of Kinopiko's answer and eval.
eval
is used here to generate the lookup table in a controlled and maintainable fashion, and a lookup table is used to save all the if.. elsif.. elsif which are not too fun to look at.(very lightly tested)
To be fully useful this needs:
Hm, if I had to do it I would do like this:
There are only so many different modifiers you might want to use so I think this is easy enough.
You can use
eval
for this, but it's awfully messy.Of course
s/$search/$replace/
work as you expect. It is the dynamic modifiers that are not straightforward.For the regular match modifiers of
pimsx
you can use Perl's Extended Patterns to modify the modifier flags on the fly as part of your pattern. These are of the form(?pimsx-imsx)
to turn on / off those modifiers.For the
s//
e
andee
forms, you can use(?{ perl code})
documented in the same perlre section. For all ofeval
e
oree
forms, consider the security of the resulting code!There is no form to modify global to first match that I am aware of, so global vs first match would need to be separate statements.