Reputation: 541
Here is the sample code:
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;
Output: Mike Xavier Smith, /123-45-1111/student, /123-45-1111/student
This line substr( $test,index($test, "/", 2) ); #offset should be from second occurrence of "/" which means it should print /student.
But why it is printing from first occurrence of "/"?
Upvotes: 1
Views: 133
Reputation: 385917
That's not what the third argument of index
is at all.
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";
Most people would just use split
.
my $test = "Mike Xavier Smith/123-45-1111/student";
my ($name, $ssn, $type) = split(qr{/}, $test);
print "$name, $ssn, $type\n";
Upvotes: 8