Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re^5: how to find this substring?

by GrandFather (Saint)
on Jun 10, 2012 at 05:04 UTC ( [id://975370]=note: print w/replies, xml ) Need Help??


in reply to Re^4: how to find this substring?
in thread how to find this substring?

Write it correctly the first time

Yes, exactly. Then dirty it up to make it go faster if you must. Your sample code is an excellent case in point. If you were processing vast numbers of strings in a highly time critical application and were doing no other processing at all then there may be some justification for using index instead of a regex match and performing the extra checking required to detect a failed match. Otherwise it's a lot clearer to go with the simple regex.

It doesn't help your argument that your unchecked substr sample code gives what would probably be considered the wrong answer when there is no match: the last character of the string. Correct handling of the no match case dirties up the index code and doubles its execution time, but the humble regex is essentially unaffected. Consider:

use strict; use warnings; use Benchmark 'cmpthese'; my $str = 'FOO' x 14 . 'ZOOCOO' . ('FOO' x 7); for my $subName (qw(doSubZ doSubB doSubX doRegZ doRegB)) { my $result = main->can($subName)->(); $result //= '--undef--'; print "$subName: $result\n"; } cmpthese( -1, { 'substrindexZ' => \&doSubZ, 'substrindexB' => \&doSubB, 'regexpZ' => \&doRegZ, 'regexpB' => \&doRegB, } ); sub doSubZ { return undef if -1 == (my $idx = index ($str, 'ZOO')); return substr ($str, $idx, 6); } sub doSubX { return substr ($str, index ($str, 'BOO'), 6); } sub doSubB { return undef if -1 == (my $idx = index ($str, 'BOO')); return substr ($str, $idx, 6); } sub doRegZ { $str =~ /(ZOO.{3})/; return $1; } sub doRegB { $str =~ /(BOO.{3})/; return $1; }

Prints:

doSubZ: ZOOCOO doSubB: --undef-- doSubX: O doRegZ: ZOOCOO doRegB: --undef-- Rate regexpZ substrindexZ substrindexB reg +expB regexpZ 1215237/s -- -45% -70% +-79% substrindexZ 2198729/s 81% -- -45% +-62% substrindexB 4003188/s 229% 82% -- +-30% regexpB 5733702/s 372% 161% 43% + --
True laziness is hard work

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://975370]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (7)
As of 2024-04-19 11:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found