为什么Perl中的索引函数在这里表现得很奇怪

时间:2012-10-04 06:29:51

标签: perl

以下是示例代码:

my $test = "Mike Xavier Smith/123-45-1111/student";
my $name = substr( $test, 0, index($test, "/") );
my $ssn = substr( $test,index($test,"/"));
my $type = substr( $test,index($test, "/", 2) );
print "$name, $ssn, $type \n";
exit;

输出: Mike Xavier Smith,/ 123-45-1111 /学生,/ 123-45-1111 /学生

此行substr($ test,index($ test,“/”,2)); #offset应该是第二次出现的“/”,这意味着它应该打印/学生 但是为什么从第一次出现“/”开始打印?

1 个答案:

答案 0 :(得分:8)

这不是index的第三个论点。

my $test = "Mike Xavier Smith/123-45-1111/student";

my $start = 0;
my $end   = index($test, "/", $start);
my $name  = substr($test, $start, $end);

$start  = $end+1;
$end    = index($test, "/", $start);
my $ssn = substr($test, $start, $end);

$start  = $end+1;
$end    = index($test, "/", $start);
my $type = substr($test, $start, $end);

print "$name, $ssn, $type\n";

大多数人只会使用split

my $test = "Mike Xavier Smith/123-45-1111/student";
my ($name, $ssn, $type) = split(qr{/}, $test);
print "$name, $ssn, $type\n";