in reply to Can a regular expression include an arbitrary string variable?
Yes, regular expressions can interpolate variables into them:
my $string_to_find = 'hidden'; my @array_to_search = qw(Foo whathiddenever Bar 12hidden456); say "Found $_" for grep {m/\Q$string_to_find/} @array_to_search;
You may also decide you don't need a pattern match, and if you can come to that conclusion you avoid the problem of treating strings as code:
say "Found $_" for grep {index($_, $string_to_find) > -1} @array_to_se +arch;
You can observe the rules of how interpolation works in regular expressions by reading perlop and perlre. The index function is also documented at perldoc -f index.
An advantage of the index approach is that you're not exposing the regular expression mini-language and engine to arbitrary strings, which could contain code. It's also lighter-weight, not invoking the engine.
Dave
|
|---|