1

这是示例代码:

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 应该从“/”的第二次出现开始,这意味着它应该打印 /student。
但是为什么它从第一次出现“/”开始打印?

4

1 回答 1

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";
于 2012-10-04T06:35:36.943 回答