【问题标题】:Try to remove specific columns using splice in Perl尝试使用 Perl 中的拼接删除特定列
【发布时间】:2013-08-22 23:34:00
【问题描述】:

我是一个全新的 Perl 新手,在我的第一个 Perl 脚本方面寻求帮助

我有一些 30-50GB 的大文件,它们是这样构造的 - 数百万列和数千行:

A B C D E 1 2 3 4 5 6 7 8 9 10 
A B C D E 1 2 3 4 5 6 7 8 9 10 
A B C D E 1 2 3 4 5 6 7 8 9 10 
A B C D E 1 2 3 4 5 6 7 8 9 10 
A B C D E 1 2 3 4 5 6 7 8 9 10 
A B C D E 1 2 3 4 5 6 7 8 9 10 
A B C D E 1 2 3 4 5 6 7 8 9 10

我想删除“A”列和“C”列,然后是数字列的三分之一,所以“3”列和“6”列,然后是“9”列,直到最后文件。空格分隔。

我的尝试是这样的:

#!/usr/local/bin/perl

use strict;
use warnings;

    my @dataColumns;
    my $dataColumnCount;
    if(scalar(@ARGV) != 2){
        print "\nNo files supplied, please supply file name\n";
        exit;
    }

    my $Infile = $ARGV[0];
    my $Outfile = $ARGV[1];

    open(INFO,$Infile) || die "Could not open $Infile for reading";
    open(OUT,">$Outfile") || die "Could not open $Outfile for writing";

    while (<INFO>) {
        chop;
        @dataColumns = split(" ");
        $dataColumnCount = @dataColumns + 1;
#Now remove the first element of the list
        shift(@dataColumns);

#Now remove the third element (Note that it is now the second - after removal of the first)
        splice(@dataColumns,1,1); # remove the third element (now the second)

#Now remove the 6th (originally the 8th) and every third one thereafter
#NB There are now $dataColumnCount-1 columns

        for (my $i = 5; $i < $dataColumnCount-1; $i = $i + 3 ) {
            splice($dataColumns; $i; 1);
        }

#Now join the remaining elements of the list back into a single string
        my $AmendedLine = join(" ",@dataColumns);

#Finally print out the line into your new file
        print OUT "$AmendedLine/n";
}

但我遇到了一些奇怪的错误:

  1. 这是说它不喜欢我在 for 循环中的 $1,我添加了一个“我的”,这似乎使错误消失了,但其他人的 for 代码似乎在这里包含一个“我的”,所以我不是确定发生了什么。

全局符号“$i”需要在 Convertversion2.pl 第 36 行显示包名。 全局符号 "$i" 需要在 Convertversion2.pl 第 36 行显示包名。 全局符号 "$i" 需要在 Convertversion2.pl 第 36 行显示包名。 全局符号“$i”需要在 Convertversion2.pl 第 36 行显示包名。

  1. 另一个错误是这样的: Convertversion2.pl 第 37 行的语法错误,“@dataColumns;”附近 Convertversion2.pl 第 37 行,“1)”附近的语法错误

我不知道如何纠正这个错误,我想我快到了,但不确定语法错误到底是什么,不确定如何修复它。

提前谢谢你。

【问题讨论】:

  • 您在写splice 行时有点脑残。首先,$dataColumns 应该是一个数组@dataColumns。其次,您应该在列表中使用逗号,而不是分号。您可以只使用数组切片,而不是使用拼接,例如print OUT join(" ", @dataColumns[1,3,4,5,6,8,9])
  • @TLP:对于 “百万列”,切片并不完全实用!
  • $dataColumnCount 在拼接时变得越来越不准确。你知道@#dataColumns 代表什么吗? splice 的结果如何影响 for 循环的增量子句的有效性?
  • @Borodin 创建要保留的索引列表就像创建要删除的索引列表一样容易。而且它肯定比用循环和诸如此类的方式来处理拼接更可取。
  • @TLP:啊,所以你想更多的是print join(' ', @dataColumns[@keep]), "\n"。也许。我很想知道这对于大型@keep 是否有效。

标签: perl split


【解决方案1】:

在我就这个问题发表博客后,一位评论者指出,可以将我的测试用例的运行时间减少 45%。我稍微解释一下他的代码:

my @keep;
while (<>) {
    my @data = split;

    unless (@keep) {
        @keep = (0, 1, 0, 1, 1);
        for (my $i = 5; $i < @data; $i += 3) {
            push @keep, 1, 1, 0;
        }
    }

    my $i = 0;
    print join(' ', grep $keep[$i++], @data), "\n";
}

这几乎是我最初解决方案所用时间的一半:

$ time ./zz.pl input.data > /dev/null
真正的 0m21.861s
用户 0m21.310s
系统 0m0.280s

现在,it is possible to gain another 45% performance 以一种相当肮脏的方式使用 Inline::C

#!/usr/bin/env perl

use strict;
use warnings;

use Inline C => <<'END_C'

/*
  This code 'works' only in a limited set of circumstances!
  Don't expect anything good if you feed it anything other
  than plain ASCII 
*/

#include <ctype.h>

SV *
extract_fields(char *line, AV *wanted_fields)
{
    int ch;
    IV current_field = 0;
    IV wanted_field = -1;

    unsigned char *cursor = line;
    unsigned char *field_begin = line;
    unsigned char *save_field_begin;

    STRLEN field_len = 0;
    IV i_wanted = 0;
    IV n_wanted = av_len(wanted_fields);

    AV *ret = newAV();
    while (i_wanted <= n_wanted) {
        SV **p_wanted = av_fetch(wanted_fields, i_wanted, 0);
        if (!(*p_wanted)) {
            croak("av_fetch returned NULL pointer");
        }
        wanted_field = SvIV(*p_wanted);

        while ((ch = *(cursor++))) {

            if (!isspace(ch)) {
                continue;
            }

            field_len = cursor - field_begin - 1;
            save_field_begin = field_begin;
            field_begin = cursor;

            current_field += 1;
            if (current_field != wanted_field) {
                continue;
            }

            av_push(ret, newSVpvn(save_field_begin, field_len));
            break;
        }
        i_wanted += 1;
    }
    return newRV_noinc((SV *) ret);
}

END_C
;

还有,这里是 Perl 部分。请注意,我们split 仅计算一次以找出要保留的字段索引。一旦我们知道了这些,我们将线和(基于 1 的)索引传递给 C 例程以进行切片和切块。

my @keep;
while (my $line = <>) {
    unless (@keep) {
        @keep = (2, 4, 5);
        my @data = split ' ', $line;
        push @keep, grep +(($_ - 5) % 3), 6 .. scalar(@data);
    }
    my $fields = extract_fields($line, \@keep);
    print join(' ', @$fields), "\n";
}
$ time ./ww.pl input.data > /dev/null
真正的 0m11.539s
用户 0m11.083s
系统 0m0.300s

input.data 是使用以下方法生成的:

$ perl -E 'say join(" ", "A" .. "ZZZZ") for 1 .. 100' > input.data

它的大小约为 225MB。

【讨论】:

  • 这行得通并且速度更快(至少你给出的第一个代码)。 Argggggg....我只能对一个答案投票,我不想不欣赏
  • 好吧,我认为我的回答会比@Borodin 的回答快得多,因为他每行做了很多很多拼接。对于一条有 300 万列的线,我们谈论的是 100 万个接头,而接头一开始并不知道是地球上最快的东西。我已经blogged about this。感谢您更改投票。
【解决方案2】:

您显示的代码不会产生这些错误。您根本没有$1,如果您的意思是$i,那么您可以使用该变量。唯一的语法错误出现在splice($dataColumns; $i; 1) 行中,它使用分号而不是逗号,并且使用$dataColumns 而不是@dataColumns

除此之外

  • 最好的做法是声明变量尽可能靠近其使用点,而不是在程序顶部。

  • 大写字母通常用于包名等常量。变量应使用小写、数字和下划线。

  • 您是否知道您将$dataColumnCount 设置为比@dataColumns 中的元素数量多一个

  • 最近不赞成使用全局文件句柄 - 您应该改用词法变量。

我建议对您的程序进行重构。它使用autodie 来避免检查open 调用是否成功。它构建了一个需要尽快删除的数组索引列表:一旦在读取第一条记录后知道每行中的字段数。然后它从末尾向后删除它们,以避免在删除前面的元素时对索引进行算术运算。

#!/usr/local/bin/perl

use strict;
use warnings;
use autodie;

if (@ARGV != 2) {
  die "\nNo files supplied, please supply file names\n";
}

my ($infile, $outfile) = @ARGV;
open my $info, '<', $infile;
open my $out,  '>', $outfile;

my @remove;

while (<$info>) {

  my @data = split;

  unless (@remove) {
    @remove = (0, 2);
    for (my $i = 7; $i < @data; $i += 3) {
      push @remove, $i;
    }
  }

  splice @data, $_, 1 for reverse @remove;

  print $out join(' ', @data), "\n";
}

【讨论】:

  • 这当然很好用,谢谢,我会研究这种替代方法,并尝试理解它,以便我可以复制它。非常感谢您的帮助。
  • 仅供参考:对于具有数百万列的行,您的代码将涉及大量拼接。
【解决方案3】:

虽然上面的其他答案完美无缺,而我的可能没有任何优势,但这是实现相同目标的另一种方法,同时避免split

#!/usr/local/bin/perl
use strict;
use warnings;
use feature 'say';

my $dir='D:\\';
open my $fh,"<", "$dir\\test.txt" or die;

while (<$fh>) {
    chomp;
    my @fields = split ' ';
    print "$fields[0] $fields[2] ";
    for (my $i=7; $i <= $#fields; $i += 3){
        print "$fields[$i] ";
    }
    print "\n";
}
close $fh;

如果这没用,请告诉我。

【讨论】:

    猜你喜欢
    • 2019-11-22
    • 2021-12-07
    • 1970-01-01
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 2013-06-26
    • 1970-01-01
    相关资源
    最近更新 更多