Capturing groups in a variable regexp in Perl
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 r开发者_StackOverflowead 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
Use qr
instead of quotes:
$regexp = qr/(\d+)\s(\d+)\s/;
$line =~ /$regexp/;
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
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
}
}
精彩评论