in reply to Re: Search a hash case insensitive
in thread Search a hash case insensitive

This code will catch duplicate IDs that are identical.
#!/usr/bin/perl -w #<SortPW2.pl> /etc/passwd sort by ID my $PASSWD="passwd"; my $fpid = open(PFILE, "<$PASSWD") or die "Password File Not Found: $! +\n"; my %ids; while (my $line = <PFILE>) { @ID = split(/:/, $line); my $id = ${ID[0]}; if ($ids{$id}) { print "'$id' is duplicate\n"; } else { $ids{$id} = 1; } }
I wish also to catch IDs that differ only in case. (ie. root , Root , ROOT) Thanx.

Replies are listed 'Best First'.
Re^3: Search a hash case insensitive
by kennethk (Abbot) on Apr 06, 2011 at 16:51 UTC
    This is tangentially discussed in How can I remove duplicate elements from a list or array?, a perlfaq. You can construct your hash, and output whenever you hit a duplicate:

    my %seen; while (my $line = <PFILE>) { @ID = split(/:/, $line); my $id = $ID[0]; if ($seen{lc($id)}++) { print "'$id' is duplicate\n"; } }

    Note you had incorrect syntax for accessing a list element. I would also recommend against using variables with the same character sequence but different cases for names.

Re^3: Search a hash case insensitive
by Eliya (Vicar) on Apr 06, 2011 at 16:49 UTC

    Just lowercase the $id you use for the hash lookup:

    my $id = $ID[0]; my $id_lc = lc $id; if ($ids{$id_lc}) { print "'$id' is duplicate\n"; } else { $ids{$id_lc} = 1; }