理解Perl匹配和索引函数

理解Perl匹配和索引函数,perl,Perl,我继承了以下Perl代码,很难理解这里的索引和匹配函数到底在做什么: my $url = $ENV{'REQUEST_URI'}; my $loc = $url; $loc =~ s/\/parks\///i; my $page = substr($loc, 0, index $loc, "_"); 我知道index(str,char)返回特定字符的索引,那么index$loc提供什么功能呢?它只是返回长度吗 我还被$loc=~s/\/parks\///I这行代码弄糊涂了与url中的短语“/p

我继承了以下Perl代码,很难理解这里的索引和匹配函数到底在做什么:

my $url = $ENV{'REQUEST_URI'};
my $loc = $url;
$loc =~ s/\/parks\///i;
my $page = substr($loc, 0, index $loc, "_");
我知道index(str,char)返回特定字符的索引,那么
index$loc
提供什么功能呢?它只是返回长度吗

我还被
$loc=~s/\/parks\///I这行代码弄糊涂了与url中的短语“/parks/”匹配。我看不出它的用途,因为无论它返回
true
还是
false
,$loc不是仍然是一个包含url的字符串吗?$page中应该包含哪些内容

我对Perl非常陌生,所以我很欣赏其中的一些细微差别,我还没有掌握

$loc =~ s/\/parks\///i;
这将从字符串$loc中删除
/parks/

my $page = substr($loc, 0, index $loc, "_");
可以写为:

# retrieve the position of the first "_" in the string $loc 
my $index = index $loc, "_";
# keep the begining of the string from position 0 to position $index
my $page = substr($loc, 0, $index);
my $page = substr($loc, 0, index($loc, "_"));
这将从字符串$loc中删除
/parks/

my $page = substr($loc, 0, index $loc, "_");
可以写为:

# retrieve the position of the first "_" in the string $loc 
my $index = index $loc, "_";
# keep the begining of the string from position 0 to position $index
my $page = substr($loc, 0, $index);
my $page = substr($loc, 0, index($loc, "_"));

Perl对括号的处理有点漫不经心,这可能会让您有点困惑。对
substr
index
的调用可以更清楚地写为:

# retrieve the position of the first "_" in the string $loc 
my $index = index $loc, "_";
# keep the begining of the string from position 0 to position $index
my $page = substr($loc, 0, $index);
my $page = substr($loc, 0, index($loc, "_"));
它在$loc中查找第一个出现的“u2;”,并在该点截断变量

此外,如果使用替代分隔符,替换运算符将更容易理解

$loc =~ s|/parks/||i;

它的意思是在$loc中“查找第一次出现的“/parks/”,并用一个空字符串替换它(即删除它)。

Perl对括号略显傲慢的处理方法可能会让您感到有点困惑。对
substr
index
的调用可能更清楚地写为:

# retrieve the position of the first "_" in the string $loc 
my $index = index $loc, "_";
# keep the begining of the string from position 0 to position $index
my $page = substr($loc, 0, $index);
my $page = substr($loc, 0, index($loc, "_"));
它在$loc中查找第一个出现的“u2;”,并在该点截断变量

此外,如果使用替代分隔符,替换运算符将更容易理解

$loc =~ s|/parks/||i;

它的意思是在$loc中“查找第一次出现的“/parks/”,并用空字符串替换它(即删除它)。

不完全正确$索引成为substr中的长度参数,因此您可以获得第一个“\u1”之前字符的所有内容$索引成为substr中的长度参数,因此您可以获得第一个“\u1”之前字符的所有内容