为什么 Perl pos() 总是返回 undef?

Why is Perl pos() always returning undef?

Perl v5.26.3

我不明白为什么这不起作用。

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

my $var = "one two three four";
$var =~ m/three/i;
print $var . "\n";
print Dumper(pos($var));
print Dumper(@-);
print Dumper(@+);

我不明白为什么 pos 总是 returns undef 无论我怎么尝试。在这种情况下,它不应该与 @+ 相同吗?

# Output from code
one two three four
$VAR1 = undef;
$VAR1 = 8;
$VAR1 = 13;

来自the documentation of pos

Returns the offset of where the last m//g search left off ...

您的代码中没有 m//g。只有 m//,没有 /g 修饰符。添加后,pos returns 预期值。