7

I'm trying to match a simple string against a regular expression pattern using the smartmatch operator:

#!/usr/bin/env perl

use strict;
use warnings;
use utf8;
use open qw(:std :utf8);

my $name = qr{/(\w+)/};
my $line = 'string';

print "ok\n" if $line ~~ /$name/;

I expect this to print "ok", but it doesn't. Why not?

ThisSuitIsBlackNot
  • 23,492
  • 9
  • 63
  • 110
abra
  • 585
  • 1
  • 5
  • 12

1 Answers1

13

Remove the slashes from your regex:

my $name = qr{(\w+)};

Since you're wrapping the regular expression in qr{}, everything inside the braces is being interpreted as the regular expression. Therefore, if you were to expand out your search, it'd be:

print "ok\n" if $line ~~ /\/(\w+)\//;

Since your string doesn't start or end with slashes (or have any substrings that do), then the match fails, and you don't print ok.

CanSpice
  • 34,814
  • 10
  • 72
  • 86