Why does smartmatch return false when I match a regex containing slashes?

I am trying to match a simple string to a regular expression pattern using the smartmatch statement:

#!/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 is not. Why not?

+7
source share
1 answer

Remove the slashes from your regex:

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

Since you end the regular expression in qr{} , everything inside the braces is interpreted as a regular expression. Therefore, if you want to expand your search, this will be:

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

Since your line does not start or end with a slash (or has any substrings), the match does not work, and you do not type ok .

+13
source

All Articles