3

I have a bunch of matches that I need to make, and they all use the same code, except for the name of the file to read from, and the regexp itself. Therefore, I want to turn the match into a procedure that just accepts the filename and regexp as a string. When I use the variable to try to match, though, the special capture variables stopped being set.

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

That 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 Answers 3

7

Use qr instead of quotes:

$regexp = qr/(\d+)\s(\d+)\s/;
$line =~ /$regexp/;
Sign up to request clarification or add additional context in comments.

Comments

4

Quote your string using the perl regex quote-like operator qr

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

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

See the perldoc page for more info: http://perldoc.perl.org/functions/qr.html

Comments

1

Quote your regex string usin qr :

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

then in the 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
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.