Chas. Owens wrote:
On Wed, Apr 9, 2008 at 4:31 PM, Jialin Li <[EMAIL PROTECTED]> wrote:
substr($string,0,2) will give you the first two digits
substr($string,5,1) will give you the sixth digit.
There are at least three downsides to using the substr function:
1. multiple function calls
2. lots of typing
3. no guarantee that the input string is in the right format
That comment surprised me. While I can agree that a regex makes it
easier to validate input, the difference in typing is insignificant, and
the regex is often more expensive to run than multiple calls for
substr(). Please see the benchmark below.
C:\home>type test.pl
use Benchmark 'cmpthese';
$str = '060001_002';
cmpthese -5, {
substr => sub {
$ch = substr $str, 0, 2;
$d = substr $str, 5, 1;
$t = substr $str, 8, 2;
($ch, $d, $t)
},
regex => sub {
$str =~ /^([0-9]{2})[0-9]{3}([0-9])_[0-9]([0-9]{2})/;
($1, $2, $3)
},
};
C:\home>test.pl
Rate regex substr
regex 507820/s -- -41%
substr 866696/s 71% --
C:\home>
--
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/