-4

我有一个数字字符串:

"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";
}
4

1 回答 1

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
于 2012-10-23T19:55:59.850 回答