For example, suppose I have a set of variables and an array of regular expressions that interpolate these variables:
my ($var1, $var2, $var3); my @search_regexes=( qr/foo $var1/, qr/foo bar $var2/, qr/foo bar baz $var3/, );
The above code will give us warnings that $var1 , $var2 and $var3 not defined at the regular expression compilation point for regular expressions in $search_regexes . However, I want to defer the interpolation variable in these regular expressions until they are used (or later (re) compiled after the variables have values):
# Later on we assign a value to $var1 and search for the first regex in $_ ... $var1='Hello'; if (/$search_regexes[0]/) {
How can I redo the construct in the source code sample to allow this?
As a bonus, I would like to compile each regular expression after the value is assigned to the corresponding variable (s) appearing in that regular expression in the same way that the qr// operator does now (but too soon). If you can show how to continue expanding the solution to do this, I would really appreciate it.
Update:
I settled on a variant of the Hunter approach because, using it, I do not accept the impact of performance and minimal changes in my existing code. Other answers also helped me a bit to find alternative solutions to this problem and their performance implications when you need to pick up a lot of lines. My code now resembles the following:
my ($var1, $var2, $var3); my @search_regexes=( sub {qr/foo $var1/}, sub {qr/foo bar $var2/}, sub {qr/foo bar baz $var3/}, ); ... ($var1,$var2,$var3)=qw(Hello there Mr); my $search_regex=$search_regexes[$based_on_something]->(); while (<>) { if (/$search_regex/) {
This gives me what I was looking for with minimal changes in my code (i.e. just adding subsets to the array up) and lack of performance when using regular expressions.
regex perl
Michael Goldshteyn
source share