Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re^2: only increment counter if the ID has not been seen before

by martin (Friar)
on Mar 12, 2015 at 10:18 UTC ( [id://1119764]=note: print w/replies, xml ) Need Help??


in reply to Re: only increment counter if the ID has not been seen before
in thread only increment counter if the ID has not been seen before

The OP wanted the same number in front of each occurence of the same ID, not a slowly increasing number counting different IDs so far. This can be achieved with a hash storing unique numbers rather than repetition counts.
use warnings; use strict; my $counter = 0; my %hash; while (<DATA>) { my @splits = split; my $snp = $splits[0]; $hash{$snp} ||= ++$counter; print "$hash{$snp} $snp\n"; } __DATA__ foo abc foo cde bar xyz foo hij
This should output:
1 foo 1 foo 2 bar 1 foo
... rather than:
1 foo 1 foo 2 bar 2 foo

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1119764]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (4)
As of 2024-04-18 00:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found