index 函数用来查找一个字符串种的字串,并返回这个字串所处的位置(从 0 开始算起)。一般使用如下代码所示:
[Perl] 纯文本查看 复制代码 #!/usr/bin/perl
$big = "hello world";
$small = "wor";
$where = index($big, $small);
print "we got at $where\n";
运行输出:
index 函数还可以使用第 3 个参数,该参数告诉函数要从哪里开始搜索:
[Perl] 纯文本查看 复制代码 #!/usr/bin/perl
my $big = "how world windows";
my $where = index($big, "w");
print "we got at $where\n";
my $where1 = index($big, "w", $where + 1);
print "we got at $where1\n";
my $where2 = index($big, "w", $where1 + 1);
print "we got at $where2\n";
运行输出:./index.pl
we got at 2
we got at 4
we got at 10
如果函数无法找到字串,那么返回 -1 。
还可以用 rindex 函数找到字串最后一次出现的位置:
[Perl] 纯文本查看 复制代码 #!/usr/bin/perl
my $path = "/home/beyes/perl/";
my $position = rindex($path, "/");
print "$position\n";
运行输出: |