Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I split a Perl string only on the last occurrence of the separator?

Tags:

split

perl

my $str="1:2:3:4:5"; my ($a,$b)=split(':',$str,2);

In the above code I have used limit as 2 ,so $a will contain 1 and remaining elements will be in $b. Like this I want the last element should be in one variable and the elements prior to the last element should be in another variable.

Example

$str = "1:2:3:4:5" ; 
# $a should have "1:2:3:4"  and $b should have "5" 
$str =  "2:3:4:5:3:2:5:5:3:2" 
# $a should have "2:3:4:5:3:2:5:5:3" and $b should have "2"
like image 473
kiruthika Avatar asked Mar 18 '10 10:03

kiruthika


1 Answers

I know, this question is 4 years old. But I found the answer from YOU very interesting as I didn't know split could work like that. So I want to expand it with an extract from the perldoc split that explains this behavior, for the sake of new readers. :-)

my $str = "1:2:3:4:5";
my ($a, $b) = split /:([^:]+)$/, $str;
# Capturing everything after ':' that is not ':' and until the end of the string
# Now $a = '1:2:3:4' and $b = '5';

From Perldoc:

If the PATTERN contains capturing groups, then for each separator, an additional field is produced for each substring captured by a group (in the order in which the groups are specified, as per backreferences); if any group does not match, then it captures the undef value instead of a substring. Also, note that any such additional field is produced whenever there is a separator (that is, whenever a split occurs), and such an additional field does not count towards the LIMIT. Consider the following expressions evaluated in list context (each returned list is provided in the associated comment):

split(/-|,/, "1-10,20", 3)
# ('1', '10', '20')

split(/(-|,)/, "1-10,20", 3)
# ('1', '-', '10', ',', '20')

split(/-|(,)/, "1-10,20", 3)
# ('1', undef, '10', ',', '20')

split(/(-)|,/, "1-10,20", 3)
# ('1', '-', '10', undef, '20')

split(/(-)|(,)/, "1-10,20", 3)
# ('1', '-', undef, '10', undef, ',', '20')
like image 198
Francisco Zarabozo Avatar answered Sep 29 '22 18:09

Francisco Zarabozo