# define these outside the loop, please. my @chars = ( "A" .. "Z", "a" .. "z", 0 .. 9, qw(! @ $ % ^ & *) ); # load the previously generated passwords from the file: my $usedpw = "logfile.txt" ; open USEDPW, "< $usedpw" or die "Error opening $usedpw for reading: $!\n"; flock USEDPW, 1; # shared lock my @used_pw = ; close USEDPW; chomp @used_pw; # and put them in a set (implemented as a hash): my %used_pw; for ( @used_pw ) { $used_pw{$_}++ } my $pw; do { # create a password: $pw = join '', @chars[map{rand @chars} (1..17)]; } while exists $used_pw{$pw}; # we now have a password which has not been used before, so report it print "Your unique password is: $pw\n"; # and store it in the file. open USEDPW, "> $usedpw" or die "Error opening $usedpw for writing: $!\n"; flock USEDPW, 2; # exclusive lock print USEDPW "$pw\n"; close USEDPW;