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

or

my ($key, $val) = 'MYKEY=MYVAL=2' =~ /^([^=]*)=(.*)/s;

Replies are listed 'Best First'.
Re^4: split command
by johngg (Canon) on Feb 21, 2007 at 19:23 UTC
    or perhaps

    my ($key, $val) = split m{=(?=.*=)}, q{MYKEY=MYVAL=2};

    Cheers,

    JohnGG

      What would be the benefit?

      • It makes needless and baseless assumption about the data format (that there will always be exactly two equal signs, no more, no less).
      • It's less readable and/or maintainable than the previously posted solutions.
      • It's probably slower than the previously posted solutions.
        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

        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