
Jasmine
Administrator
/ Moderator
Mar 23, 2001, 12:01 AM
Post #2 of 5
(489 views)
|
Uncommented version
#!/usr/bin/perl -w my %hash; open ( DATA, "<users.txt" ) or die "Can't open data file $!\n"; while ( <DATA> ){ chomp; my ( $user, $pw ) = split( /:/ ); unless ( exists $hash{$user} ){ $hash{$user} = $pw if $user; } else { EXISTS : while ( each %hash ){ $user++; redo EXISTS if exists $hash{$user}; $hash{$user} = $pw; last EXISTS; } } } close DATA or die "Can't close data file $!\n"; for my $user (sort { $a <=> $b } keys %hash ){ print "User: $user Password: $hash{$user} \n"; } Commented version:
#!/usr/bin/perl -w my %hash; open ( DATA, "<users.txt" ) or die "Can't open data file $!\n"; while ( <DATA> ){ chomp; # first, extract username/pw from line my ( $user, $pw ) = split( /:/ ); # now, if the username hasn't already been read, toss it into the hash unless ( exists $hash{$user} ){ $hash{$user} = $pw if $user; } else { # this part will only be run if it's a duplicate username. # we can't just increment it because we don't want to assume that # simply incrementing it will make it unique. So we're going to # loop through the keys of the hash to make sure it's not already # defined. # I like to use loop labels. This makes it very easy to # remember what's going on when you have to review the code 3 # months later, or if you're nesting loops. Also note that # we're using the redo and last, which makes labels necessary # if loops are being nested. EXISTS : while ( each %hash ){ # start off the loop with incrementing the username $user++; # if the incremented version exists, start again (note # that the username is still incremented) redo EXISTS if exists $hash{$user}; # if we've incremented the username to the point where # it's now unique, then the redo will not run and # we get to this point. Assign the hash value and # last out of the loop. $hash{$user} = $pw; last EXISTS; } } } close DATA or die "Can't close data file $!\n"; for my $user (sort { $a <=> $b } keys %hash ){ print "User: $user Password: $hash{$user} \n"; } # now you have a hash that's propagated with unique usernames # as the key and the password as the key's value.
|