在Perl中拆分数字字符串

时间:2012-10-23 19:36:19

标签: string perl split

我有一个数字字符串:

"13245988"

我想在连续数字之前和之后拆分。

预期输出为:

1
32
45
988

这是我尝试过的:

#!/usr/bin/perl
use strict;
use warnings;

my $a="132459";
my @b=split("",$a);
my $k=0;
my @c=();
for(my $i=0; $i<=@b; $i++) {
    my $j=$b[$i]+1;
    if($b[$i] == $j) {
        $c[$k].=$b[$i];
    } else {
        $k++;
        $c[$k]=$b[$i];
        $k++;
    }
}
foreach my $z (@c) {
    print "$z\n";
}

1 个答案:

答案 0 :(得分:0)

根据澄清的问题进行编辑。这样的事情应该有效:

#!/usr/bin/perl
use strict;
use warnings;

my $a = "13245988";
my @b = split("",$a);

my @c = ();
push @c, shift @b; # Put first number into result.

for my $num (@b) { # Loop through remaining numbers.

    my $last = $c[$#c] % 10; # Get the last digit of the last entry.

    if(( $num <= $last+1) && ($num >= $last-1)) {
        # This number is within 1 of the last one
        $c[$#c] .= $num; # Append this one to it
    } else {
        push @c, $num; # Non-consecutive, add a new entry;
    }
}

foreach my $z (@c) {
    print "$z\n";
}

输出:

1
32
45
988