On Mon, Jun 28, 1999 at 11:20:20AM -0700, Vicki Brown wrote: > Specifically, the line which illustrates (to me) TMTOWTDI (but some are > wrong) is: > if ( index( $szPhdFile, ".phd." ) >= 0 ) { How does this line illustrate that some ways are wrong? This line of code works just fine. > My thoughts when reviewing this code ran as follows: "Now, why would > someone who appears to understand pattern matching and substitution be > using index here... Is there a method to the madness? > > > I would have used > > if ($szPhdFile =~ /\.phd\./) { > Why would someone who understands index use pattern matching to find a constant substring? #!/usr/local/bin/perl use Benchmark; $short = 'short (.phd.) string'; $long = ('long ' x 100) . '(.phd.)' . (' string' x 100); timethese(1 << shift, { index_s => sub { index ($short, '.phd.') >= 0 }, index_l => sub { index ($long, '.phd.') >= 0 }, regex_s => sub { $short =~ /\.phd\./ }, regex_l => sub { $long =~ /\.phd\./ }, }); __END__ Benchmark: timing 65536 iterations of index_l, index_s, regex_l, regex_s... index_l: 1 secs ( 2.07 usr 0.00 sys = 2.07 cpu) index_s: 1 secs ( 0.92 usr 0.00 sys = 0.92 cpu) regex_l: 1 secs ( 1.47 usr 0.00 sys = 1.47 cpu) regex_s: 1 secs ( 1.21 usr 0.00 sys = 1.21 cpu) It appears that index is faster for short target strings, but regex is faster for long target strings. (With perl5.004, anyway.) I expect that the path to a file would be 'short'... Anyway, given that the code works perfectly, and that index() is an accepted method of finding constant substrings, I don't think this one qualifies as a 'What was he thinking?' (What were you thinking? *grin* Sorry.) Ronald ==== Want to unsubscribe from Fun With Perl? ==== Well, if you insist... Send mail with body "unsubscribe" to ==== fwp-request@technofile.org