in reply to Splitting on a pattern once

Check out split's 3rd arg.
my ($k,$v) = split(/:/, $_, 2);

Replies are listed 'Best First'.
Re^2: Splitting on a pattern once
by ungalnanban (Pilgrim) on Mar 05, 2010 at 10:49 UTC

    Is there any way to split the string from last occurrence.?
    I tried with positive values and negative value in 3rd argument of split().
    --sugumar--
      Is this you are expecting.
      Example-1
      my $str="1 2 3 4 590"; my ($a,$b)=split(/ ([^ ]+)$/, $str); print "a=$a\nb=$b\n";

      Output
      a=1 2 3 4
      b=590

      Example-2
      my $str="1:2:3:4:590"; my ($a,$b)=split(/:([^:]+)$/, $str); print "a=$a\nb=$b\n";

      Output
      a=1:2:3:4
      b=590
      Use the following way to achieve your requirement.
      my $str="1:2:3"; my $name=(split(':',$str))[-1];
      -1 will return the value of last index.
      You could play with reverse, but this is simpler:
      my ($k,$v) = /^(.*:)?(.*)/s;
      You should read the documentation for split as a negative limit has special meaning.