in reply to Re^4: split command
in thread split command

What would be the benefit?

Replies are listed 'Best First'.
Re^6: split command
by johngg (Canon) on Feb 22, 2007 at 00:22 UTC
    Using index and substr seems to be quicker still.

    use strict; use warnings; use Benchmark q{cmpthese}; my $rsIndex = sub { my $str = q{MYKEY=MYVAL=2}; my $pos = index $str, q{=}; my $key = substr $str, 0, $pos; my $val = substr $str, $pos + 1; return [$key, $val]; }; my $rsMatch = sub { my ($key, $val) = q{MYKEY=MYVAL=2} =~ /^([^=]*)=(.*)/s; return [$key, $val]; }; my $rsSplit = sub { my ($key, $val) = split m{=(?=.*=)}, q{MYKEY=MYVAL=2}; return [$key, $val]; }; cmpthese(-5, { Index => $rsIndex, Match => $rsMatch, Split => $rsSplit });
    Rate Split Match Index Split 26498/s -- -6% -33% Match 28068/s 6% -- -29% Index 39627/s 50% 41% --

    Cheers,

    JohnGG

Re^6: split command
by johngg (Canon) on Feb 21, 2007 at 23:54 UTC
    What would be the benefit?

    None that I can think of. Just showing that TIMTOWTDI.

    It makes needless and baseless assumption ...

    Agreed. The OP asks to split on first occurance of an equals sign. It doesn't say what to do if there's more than two equals signs so assumptions are invalid, even the assumption that splitting on first occurance is still the requirement when there are three or more of them.

    It's less readable and/or maintainable ...

    my ($key, $val) = 'MYKEY=MYVAL=2' =~ /^([^=]*)=(.*)/s; my ($key, $val) = split m{=(?=.*=)}, q{MYKEY=MYVAL=2};

    Six of one, a half dozen of the other, I'd say.

    It's probably slower ...

    Yes, about 8% slower if my benchmark code is correct

    use strict; use warnings; use Benchmark q{cmpthese}; my $rsMatch = sub { my ($key, $val) = q{MYKEY=MYVAL=2} =~ /^([^=]*)=(.*)/s; return [$key, $val]; }; my $rsSplit = sub { my ($key, $val) = split m{=(?=.*=)}, q{MYKEY=MYVAL=2}; return [$key, $val]; }; cmpthese(-5, { Match => $rsMatch, Split => $rsSplit });
    Rate Split Match Split 26064/s -- -8% Match 28250/s 8% --

    Cheers,

    JohnGG