in reply to How can I keep the first occurrence from duplicated strings?

For fun, a more verbose version that you might find easier to understand or maintain:

# print-first.pl. See Perl Monks [id://11154123]. use strict; use warnings; my $fname = shift or die "usage: $0 file\n"; open( my $fh, '<', $fname ) or die "error: open '$fname': $!"; my %hash; my $line; while ( defined($line = <$fh>) ) { chomp $line; $line =~ s/^\s+//; # remove leading $line =~ s/\s+$//; # and trailing whitespace next unless length $line; # ignore empty lines next if $line =~ /^#/; # ignore comment lines next unless $line =~ /^(\w+)\s+(\d+)$/; # ignore lines that do no +t match my $key = $1; my $val = $2; next if exists $hash{$key}; # ignore if already seen ++$hash{$key}; print "$key $val\n"; } close $fh;

Example run:

$ cat t1.txt nick 5 nick 10 nick 20 john 78 erik 9 erik 12

$ perl print-first.pl usage: print-first.pl file $ perl print-first.pl t1.txt nick 5 john 78 erik 9

See Also

Updated: Added "See Also" section