http://blog.sina.com.cn/s/blog_4af3f0d20100g73p.html编个程序,实现一下功能:连续数组(相差为1)只输出首尾两个
例如:
1
2
3
7
8
9
输出
1-3
7-9
记得以前论坛有过这个程序,忘记了,现在也没找到
说明,上面只是一个例子,说明问题用的,
答案1:
# cat sort.pl
use strict;
my @x=(1,2,3,7,8,9,13,17,18,19,22);
my @tmp;
for (my $i=0;$i<=$#x;$i++) {
push @tmp,$x[$i];
if ($x[$i]+1 != $x[$i+1]) {
my $re=join "-",$tmp[0],$tmp[-1];
print $re,"\n"; @tmp=();
}
}
# perl sort.pl
1-3
7-9
13-13
17-19
22-22
答案2:
#!/usr/bin/perl
####### 前提:数据按照从小到大或从大到小的顺序排好 #########
####### #########
$first_value=1;
@a=($first_value);
while(<DATA>){
chomp;
if( $b+1==$_||$b-1==$_){
push @a,$_;
$b=$_;
}
else{
print "$a[0]\t$a[-1]\n";
$b=$_;
@a=();