A. Sinan Unur writes a what if troll:
So, who's on third?
What if, what if, what if, how very lame.
No, not realizing when a particular piece of code might fail is lame.
Since there was no such caution in the code you posted, I was pointing
out the pitfalls for other impressionable readers out there.
....
"Perl currently has no function to return an index number for a
specific array element nor substring of a specific array element. This
snippet exemplifies a quick and easy method to determine an element
index number. Caution should be exercised to not use a record
separator delimiter which is found within one or more array entries.
Use of a broken pipe symbol is usually safe. Do not ignore this
cautionary note.
So, the code you posted might return wrong results, but there is no way
for a user of that code to check the validity of the result ... Hmmm.
This method can be used to address an element with $Array[n] syntax as
shown in my final print. This aids in programming to manipulate a
specific element when its precise array location is unknown."
No, it doesn't, because you cannot be certain that the index found by
the code you posted actually refers to an element of the array
containing the substring you are looking for.
And, since you like benchmarks:
#!/usr/bin/perl
use strict;
use warnings;
use Benchmark 'cmpthese';
my @arr = ("Purl", "Girl Rocks", "And Gurl Rolls!");
sub my_index_of_element {
my $i = 0;
while (-1 == index $arr[$i], 'Gurl') {
$i += 1;
return -1 if $i == @arr;
}
return $i;
}
sub pg_index_of_element {
local $" = "¦";
(substr ("@arr", 0, index ("@arr", "Gurl"))) =~ tr/¦//;
}
cmpthese -1, {
my_index_of_element => \&my_index_of_element,
pg_index_of_element => \&pg_index_of_element,
};
D:\Home\asu1\UseNet\clpmisc> ai
Rate pg_index_of_element my_index_of_element
pg_index_of_element 142315/s -- -28%
my_index_of_element 196887/s 38% --
Sinan