操纵Perl数据系列

时间:2015-05-26 10:23:27

标签: perl

我有一个数组Say @array1 = qw (1,1,1,2,3,4,4,4,5,6,1,1,1)。从这个数组我必须提取一个输出为"1,1,1,2,3,4,4,4,5,6"(即从单独的末尾删除1的数量)。实际上我尝试了其他类似问题的不同方法建议,但我无法实现。我是Perl的新手,请帮帮我。

P.S。:系列可以按任何顺序排列。不一定是提升,可以是1之间的任何随机数。在价值' 5'之间&安培; ' 6',如下所示,也不会有任何1。说:

my @array1 = (1,1,1,5,3,4,4,4,2,6,1,1,1,1,1);

预期产出:

(1,1,1,5,3,4,4,4,2,6)

模糊的步骤,但无法到达我想要的地方:

my $file = "emm4.txt"; #emm4.txt contains 1,1,1,2,3,4,4,4,5,6,1,1,1

open (FH, "< $file") or die "Can't open $file for read: $!";
my @lines;
while (<FH>) {
push (@lines, $_);
}    
sub UniqueValues {
my %seen;
return grep { !$seen{$_}++ } @_;
   }  
my @unique;
@unique = UniqueValues(@lines);
print @unique;

close FH or die "Cannot close $file: $!";

2 个答案:

答案 0 :(得分:0)

您的UniqueValues功能正确无误。问题可能在于您对输入的处理。调试此方法(除了使用内置调试器之外)的一种快速方法是使用JSON,YAML或其他一些目标文本的序列化格式来转储@lines的值内容。为简单起见,我将使用Data::Dumper模块,因为它是Core Perl的一部分:

#!/usr/bin/env perl

use strict;
use warnings;

use Data::Dumper;

my $file = "emm4.txt"; #emm4.txt contains 1,1,1,2,3,4,4,4,5,6,1,1,1

# always use the three argument version of open or you have a 
# a security hole (see open's documentation for more)
# also, bareword filehandles have issues, lexical filehandles
# are better
open my $fh, "<", $file or die "Can't open $file for read: $!";

my @lines;
while (my $line = <$fh>) {
    chomp $line; #this is needed or there will be a newline at the end of the line
    push (@lines, $line);
}

print Dumper \@lines;

如果不打印

$VAR1 = [
          1,
          1,
          1,
          2,
          3,
          4,
          4,
          4,
          5,
          6,
          1,
          1,
          1
        ];

然后你对文件中的数据做错了。从您的评论中,您似乎表明该文件包含&#34; 1,1,1,2,3,4,4,4,5,6,1,1,1和#34;如果是这样,那么您可能需要查看split函数。

答案 1 :(得分:-1)

<强>更新

从您的评论中看起来您需要减少尾随数组值,直到最终值为唯一

试试这个,但请注意它会删除任何重复值。例如,6 1 5 2 4 3 7 7 7将缩减为6 1 5 2 4 3 79 1 1 1 1 1 3将保持不变

use 5.014;

use strict;
use warnings;

my @array = qw(1 1 1 2 3 4 4 4 5 6 1 1 1 );

say "@array";

pop @array while @array > 1 and $array[-1] == $array[-2];

say "@array";

<强>输出

1 1 1 2 3 4 4 4 5 6 1 1 1
1 1 1 2 3 4 4 4 5 6 1

<强>原始

看起来你需要的只是

pop @array1 while $array1[-1] == 1;

但是您的输入很困惑,除非您展示数据文件的准确示例,否则我无法告诉您如何修复它

文件中的数字是否每行一个?然后,您需要做的就是在读取循环之后chomp @array1

文件中只有一行用逗号分隔的数字?那么你只需要@array1 = /\d+/g