[sf-perl] Plucking from a string

Sergey Fetisov sergey.fetisov at ask.com
Fri May 23 16:01:36 PDT 2008


Faster, but not always (as far as much more memory is required in an
array context).
So it depends from the string size and how much memory has been
allocated by the script before.
Occasionally the memory allocation takes some time :) and adds some cost
Below my small example and I hope it shows the difference

#!/usr/bin/perl -wT
use Time::HiRes qw(gettimeofday tv_interval); # CPAN:
use strict;

my $theline = "vvvbcd=7wwwbcd=88xxxbcd=999yyybcd=1000zzz";
my $TARGETSTR = "bcd=";

for my $i (1..3) {
    $theline .= $theline foreach (0..($i-1)*6);
    print "EXPERIMENT $i: Length of the string ${\length($theline)}\n";

print "LAST EXPERIMENT REPEAT: Length of the string

sub methodA {
    my ($interval, $count);
    $interval = [gettimeofday];
    while ($theline =~ /($TARGETSTR\d+)/gi) { $count++; }
    $interval = tv_interval ( $interval );
    print "\tMethod A: $count matches found, processing time:

sub methodB {
    my ($interval, $count);
    $interval = [gettimeofday];
    my $TARGET = qr/(?i:bcd=\d+)/;
    $count++ for ( $theline =~ /$TARGET/g );
    $interval = tv_interval ( $interval );
    print "\tMethod B: $count matches found, processing time:

= Sergey

-----Original Message-----
From: sanfrancisco-pm-bounces+sergey.fetisov=ask.com at pm.org
[mailto:sanfrancisco-pm-bounces+sergey.fetisov=ask.com at pm.org] On Behalf
Of frosty
Sent: Thursday, May 22, 2008 6:35 PM
To: San Francisco Perl Mongers User Group
Subject: Re: [sf-perl] Plucking from a string

Here's a minor variation, which I think should be a little faster.

my $theline = "vvvbcd=7wwwbcd=88xxxbcd=999yyybcd=1000zzz";

my $TARGET = qr/(?:bcd=\d+)/; # safer to precompile the whole regex

print "$_\n" for ( $theline =~ /$TARGET/g );

-- f.


More information about the SanFrancisco-pm mailing list