> > How do I truncate a string to a particular number of characters?
> >
> You can use the substr() function, or optimize your regex:
>
> #!/usr/bin/perl -w
> use strict;
>
> my $string;
>
> # with substr
> $string = "hello word";
> $string = substr($string,0,4);
> print "substr: $string\n";
>
> # with a regex
> $string = "hello word";
> $string =~ s/^(.{4}).*/$1/;
> print "regex: $string\n";
> __END__
>
>
> --
> briac
> << dynamic .sig on strike, we apologize for the inconvenience >>
substr 0 wallclock secs ( 0.31 usr + 0.00 sys = 0.31 CPU)
regex 2 wallclock secs ( 1.99 usr + 0.00 sys = 1.99 CPU)
Thanks, substr over 6 times faster, looks like I get to use it for the first
time.
Gary
#!/usr/bin/perl -w
use Benchmark;
$t0 = new Benchmark;
my $string;
# with substr
for (1 .. 100000) {
$string = "hello word";
$string = substr($string,0,4);
}
$t1 = new Benchmark;
$td = timediff($t1, $t0);
print timestr($td) . "\n";
$t0 = new Benchmark;
# with a regex
for (1 .. 100000) {
$string = "hello word";
$string =~ s/^(.{4}).*/$1/;
}
$t1 = new Benchmark;
$td = timediff($t1, $t0);
print timestr($td) . "\n";
__END__
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]