[英]Perl: Regular Expression for finding first occurence per line? (EditPad)
[英]How to put the first occurence of a line in a file into a %hash with Perl?
例如,给定此数据:
ID1 2 3 4
ID1 2 4 5
ID2 2 6 8
ID2 4 6 7
ID3 3 5 6
我想读取文件句柄并以第一行循环遍历它,直到ID与先前的ID不匹配,然后继续直到文件结尾,所以我的输出文件如下所示:
ID1 2 3 4
ID2 2 6 8
ID3 3 5 6
任何帮助是极大的赞赏。 谢谢。
perl -ane '$s{$F[0]}++ or print' file
use warnings;
use strict;
use Data::Dumper;
open my $in, '<', 'in.txt';
my %data;
while (<$in>){
chomp;
my @split = split(/\s+/);
next if exists $data{$split[0]};
$data{$split[0]} = [$split[1], $split[2], $split[3] ];
}
print Dumper \%data;
或者,就像@mpapec的解决方案一样,但作为匿名哈希( %_
):
perl -ane '${$F[0]}++ or print' file.txt
那时我真的只是在做愚蠢的代码高尔夫。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.