tags:

views:

370

answers:

4

Hi All,

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"
+4  A: 
split(/:([^:]+)$/, $str)
S.Mark
Thanks a lot......
kiruthika
+1  A: 

You can do it using split and reverse as follows:

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

$a = reverse($a); # reverse each piece.
$b = reverse($b);

($a,$b) = ($b,$a); # swap a and b

Now $a will be 1:2:3:4 and $b will be 5.

A much simpler and cleaner way is to use regex as Mark has done in his Answer.

codaddict
While this is a possibility, it isn't exactly efficient, especially when a single line will do the equivalent. Something like `my ($a,$b) = ($str =~ /(.*):(.?)/);`
Zaid
+3  A: 

you can also use rindex() eg

my $str="1:2:3:4:5";
$i=rindex($str,":");
$a=substr($str,0,$i);
$b=substr($str,$i+1);
print "\$a:$a, \$b: $b\n";

output

$ perl perl.pl
$a:1:2:3:4, $b: 5
ghostdog74
Since the split separator is so simple in this case, this is a faster solution than using a regex to parse through the entire expression trying to bind to `$`.
Ether
+3  A: 

You can use matching, instead of split:

my ($a,$b) = $str =~ /(.*):(.*)/;
eugene y
I'd make that second `.*` a `.?`, just to be sure.
Zaid