Capturing groups in regexp variable in Perl

I have a bunch of matches that I need to make, and they all use the same code, except for the file name to read and the regular expression itself. So I want to turn the match into a procedure that just takes the file name and regular expression as a string. When I use a variable to try to match, special fixed variables cease to be set.

$line =~ /(\d+)\s(\d+)\s/;

This code sets $ 1 and $ 2 correctly, but the following leaves them undefined:

$regexp = "/(\d+)\s(\d+)\s/";
$line =~ /$regexp/;

Any ideas how I can get around this?

Thanks Jared

+3
source share
3 answers

Enter the usin qr regex string:

my $regex = qr/(\d+)\s(\d+)\s/;
my $file =q!/path/to/file!;
foo($file, $regex);

and then in sub:

sub foo {
my $file = shift;
my $regex = shift;

open my $fh, '<', $file or die "can't open '$file' for reading: $!";
while (my $line=<$fh>) {
    if ($line =~ $regex) {
        # do stuff
    }
}
+1
source

qr :

$regexp = qr/(\d+)\s(\d+)\s/;
$line =~ /$regexp/;
+7

, relx perl qr

$regexp = qr/(\d+)\s(\d+)\s/;

This statement quotes (and possibly compiles) its STRING as a regular expression.

See perldoc for more information: http://perldoc.perl.org/functions/qr.html

+4
source

Source: https://habr.com/ru/post/1755349/


All Articles