in reply to split a string at a defined index

You can split at the last comma by using a lookahead to check there are no more commas:

print for split /,(?=[^,]+$)/, "www,google,yahoo,345";; www,google,yahoo 345

Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
"I'd rather go naked than blow up my ass"

Replies are listed 'Best First'.
Re^2: split a string at a defined index
by AnomalousMonk (Archbishop) on Mar 29, 2010 at 08:09 UTC

    ... and  split on a specific index (without using substr):

    >perl -wMstrict -le "my $s = 'www,google,yahoo,345'; my ($v1, $v2) = split m{ (?<= \A .{16}) , }xms, $s; print qq{[$v1] [$v2]}; " [www,google,yahoo] [345]

      I suspect that by "at a defined index", the IP meant "the third comma" rather than "the 16th character position".

      If he does mean the 16th position, using substr is far clearer and vastly more efficient.


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.