【发布时间】:2015-12-07 17:47:55
【问题描述】:
类似于问题 unix - count occurrences of character per line/field 但对于该行每个位置的每个字符。
给定一个每 1e7 行约 500 个字符的文件, 我想要一个二维摘要结构,例如 $summary{'a','b','c','0','1','2'}[pos 0..499] = count_integer 它显示了每个字符在该行的每个位置使用的次数。任何一种尺寸顺序都可以。
我的第一个方法在阅读时执行了 ++summary{char}[pos], 但由于许多行是相同的, 首先计算相同的行要快得多, 然后总结 summary{char}[pos] += n 一次
是否有比以下类似 C 的 2d 循环更惯用或更快的方法?
#!perl
my ( %summary, %counthash ); # perl 5.8.9
sub method1 {
print "method1\n";
while (<DATA>) {
my @c = split( // , $_ );
++$summary{ $c[$_] }[$_] foreach ( 0 .. $#c );
} # wend
} ## end sub method1
sub method2 {
print "method2\n";
++$counthash{$_} while (<DATA>); # slurpsum the whole file
foreach my $str ( keys %counthash ) {
my $n = $counthash{$str};
my @c = split(//, $str);
$summary{ $c[$_] }[$_] += $n foreach ( 0 .. $#c );
} #rof my $str
} ## end sub method2
# MAINLINE
if (rand() > 0.5) { &method1 } else { &method2 }
print "char $_ : @{$summary{$_}} \n" foreach ( 'a', 'b' );
# both methods have this output summary
# char a : 3 3 2 2 3
# char b : 2 2 3 3 2
__DATA__
aaaaa
bbbbb
aabba
bbbbb
aaaaa
【问题讨论】:
-
使用该示例数据很难想象您要查找的内容 - 我假设您的场景不像一行充满重复字符的行那么简单?另外:
use strict; use warnings;是个好主意。 -
我看到的唯一低效率/非惯用性(?)是您也在计算所有行终止字符(换行符和/或 CR)。 (Perl 将它们包含在
$_中,除非你做某事。)在每个<DATA>读取后插入chomp;。 -
@JeffY: unidiomaticity,我相信
-
这些是DNA序列吗?
-
真实数据是 TDL,一种使用字符 HLCM01Z 的 VHDL 向量形式,我正在寻找使用哪些引脚/列与静态。我有使用警告;使用严格;在实际程序中,但我忽略了将它们包含在示例程序中以进行发布。索布里克。杰夫·鲍罗丁