in reply to Search a hash case insensitive

Depending on what exactly you need this for, you could maybe transform all keys to the same case (e.g. lower-case) before you put the entries in the hash — in which case you can then do a direct lookup.

Replies are listed 'Best First'.
Re^2: Search a hash case insensitive
by Saved (Beadle) on Apr 06, 2011 at 16:44 UTC
    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.
      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.

      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; }