Let's look at your code:
$var = "AB1234567";
$num = "1234567";
next if $var =~ /$num/;
print "Success!\n";
I am assuming this is in the body of some loop. When you say
next if $var =~ /$num/;
You are saying "go back and execute the loop body for the next iteration, skipping any following statements in the look body if $var
matches /$num/
". When $var
does indeed match /$num/
, the program does exactly what you asked for and skips the print
statement.
On the other hand, when you use $var =~ /"$num"/
, the pattern on the right hand side becomes /"1234567"/
. Now, the conditional in next if $var =~ /"$num"/
cannot succeed. And, your program prints "Success"
because the match failed.
#!/usr/bin/perl
use strict; use warnings;
use re 'debug';
my $num = "1234567";
for my $var ( qw( AB1234567 ) ) {
next if $var =~ /$num/;
print "Success!\n";
}
Output:
Compiling REx "1234567"
Final program:
1: EXACT (4)
4: END (0)
anchored "1234567" at 0 (checking anchored isall) minlen 7
Guessing start of match in sv for REx "1234567" against "AB1234567"
Found anchored substr "1234567" at offset 2...
Starting position does not contradict /^/m...
Guessed: match at offset 2
Freeing REx: "1234567"
Now, let's use /"$num"/
as the pattern:
#!/usr/bin/perl
use strict; use warnings;
use re 'debug';
my $num = "1234567";
for my $var ( qw( AB1234567 ) ) {
next if $var =~ /"$num"/;
print "Success!\n";
}
Output:
Compiling REx "%"1234567%""
Final program:
1: EXACT (5)
5: END (0)
anchored "%"1234567%"" at 0 (checking anchored isall) minlen 9
Guessing start of match in sv for REx "%"1234567%"" against "AB1234567"
Did not find anchored substr "%"1234567%""...
Match rejected by optimizer
Success!
Freeing REx: "%"1234567%""
Your code prints Success! when the match fails.
See also perldoc perlsyn:
The next
command starts the next iteration of the loop:
LINE: while (<STDIN>) {
next LINE if /^#/; # discard comments
...
}