user2344516
user2344516

Reputation: 55

How to put the first occurence of a line in a file into a %hash with Perl?

For example, given this data:

ID1 2 3 4 
ID1 2 4 5 
ID2 2 6 8
ID2 4 6 7 
ID3 3 5 6 

I would like to read a file handle and loop through it taking the first line until the ID does not match the previous ID and then continue till end of file so my output file looks like:

ID1 2 3 4 
ID2 2 6 8 
ID3 3 5 6

Any help is greatly appreciated. Thank you.

Upvotes: 0

Views: 71

Answers (3)

G. Cito
G. Cito

Reputation: 6378

Or, like @mpapec's solution but as an anonymous hash (%_):

perl -ane '${$F[0]}++ or print' file.txt

At that point I'm really just doing silly code golf though ....

Upvotes: 0

fugu
fugu

Reputation: 6578

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;

Upvotes: 2

mpapec
mpapec

Reputation: 50647

perl -ane '$s{$F[0]}++ or print' file 

Upvotes: 4

Related Questions