in reply to regex needed

There's no need to split in so many parts. The next will reduce the amount of work actually done:
(undef, my $foo) = split /:/;
as it will split into 3 parts, throwing away the first (leading) and third (rest) parts. Compare:
$foo = (split/:/)[1];
will split into as many parts as there are columns. So will
@data = split/:/; $foo = $data[1];

Do you insist on a regex? I don't know if anybody gave you one already, as everybody seems to be focussing on split... Here is one:

($foo) = /:(.*?):/;
Note that your requirement makes this easy... making me feel like this is homework. If you wanted another column, like the fourth one, the regex would look really messy.

Replies are listed 'Best First'.
Re: Re: regex needed
by tall_man (Parson) on Mar 14, 2003 at 19:11 UTC
    it will split into 3 parts

    I'm not sure there's any guarantee perl will do that optimization for you. If you want three parts, just tell it so:

    $foo = (split/:/,$_,3)[1];
    Update: You seem to be right about the optimization. The following benchmark shows nearly identical times:
    cchan.acsys.com.1.256% cat aaa3.pl use Benchmark; my $count = 1000000; our $str = "a:b:c:d:e:ff:g:h:i:j:k:l:m:n:o:p:q:r:s:t:u:v:w:x:y:z"; timethese($count, { 'slice' => sub { (undef, my $foo) = split /:/,$str; }, 'count' => sub { my $foo = (split/:/,$str,3)[1]; }, });
    Benchmark: timing 1000000 iterations of count, slice... count: 2 wallclock secs ( 3.18 usr + 0.01 sys = 3.19 CPU) @ 31 +3479.62/s (n=1000000) slice: 3 wallclock secs ( 3.04 usr + 0.06 sys = 3.10 CPU) @ 32 +2580.65/s (n=1000000)
    However, giving the split limit explicitly is clearer IMHO.
      I'm not sure there's any guarantee perl will do that optimization for you.
      Yes it's garanteed. I'll just have to find the proper documentation for you... Ah, here it is, in perldoc -f split:
      When assigning to a list, if LIMIT is omitted, Perl supplies a LIMIT one larger than the number of variables in the list, to avoid unnecessary work.
      Therefore, with two scalars on the left hand side (of which one variable, and undef), Perl will split into 3 parts.