in reply to backward split

Here is one way:
#!/usr/bin/perl -w use strict; my $string = "foo.bar.foobar"; my ($val1,$val2) = (split /\./,$string)[-2,-1]; print "$val1,$val2\n";
update: This returns the last two items in a split, not the item split on the last pattern, as the OP had intended.

-enlil

Replies are listed 'Best First'.
Re: Re: backward split
by Anonymous Monk on Jun 01, 2003 at 00:51 UTC
    This does not work because it splits the foo.bar portion of the string, which should remain intact according to normal split usage, when split is supplied with a limit.
      Sorry, misinterpreted your intent. This should work to split it that way then:
      #!/usr/bin/perl -w use strict; my $string = "foo.bar.foobar"; my ($val1,$val2) = split /\.(?!.*\.)/,$string; print "$val1,$val2\n";

      update:and another way:

      #!/usr/bin/perl -w use strict; my $string = "foo.bar.foobar"; my $position = rindex($string,'.'); my ($val1,$val2) = ( substr($string,0,$position++), substr($string,$position) ); print "$val1,$val2\n";
      update:Apparently, I suffer from not enough laziness, as in the end would probably have kept thinking there has to be a more elegant solution, and would hopefully stumbled upon sauoq's solution below at some point, which I think is the best solution, but leave the above code if only to show TMTOWTDI.

      -enlil

        Of course, you can use a positive lookahead too...

        my ($val1, $val2) = split /\.(?=[^.]*$)/, $string;
        but really... neither choice is better than a simple capturing regex.

        -sauoq
        "My two cents aren't worth a dime.";