in reply to reading from file.
G'day scripter87,
You haven't really provided sufficient information. "it works" and "it dont" and spectacularly useless error reports. You haven't shown how you're testing this: i.e. what you're using for input. You haven't shown your data: there could be line ending and embedded whitespace issues. A better question gets better answers: take a look at the guidelines in "How do I post a question effectively?" to see how you can achieve this.
There's issues with the code as posted. It will print "not valid" for every record in names.txt until it either finds a match or reaches EOF. I see Eily pointed out an issue with $names: you said this was a typo; if you copy and paste your actual code, this won't happen. Do you really want to open/read/close the entire file for every "my $input = <STDIN>;"? Do you allow more than one attempt?
Here's a potentially better way to do what you want:
#!/usr/bin/env perl use strict; use warnings; use autodie; my $name_file = 'names.txt'; open my $name_file_fh, '<', $name_file; chomp(my @names = <$name_file_fh>); close $name_file_fh; print 'Enter login name: '; chomp(my $input = <STDIN>); print "Invalid!\n" unless grep { $_ eq $input } @names;
Note that you can wrap the 'Enter login name: ' part in a loop to allow multiple attempts without having to reread the file. Not shown in your posted code, so I haven't tried to make guesses here, but you'll need to code some sort of successful login actions.
Update: Prompted by Eily's mention of a hash and exists, which I saw after posting, this would be an improvement on what I originally provided:
#!/usr/bin/env perl use strict; use warnings; use autodie; my $name_file = 'names.txt'; open my $name_file_fh, '<', $name_file; my %name = map { chomp; $_ => 1 } <$name_file_fh>; close $name_file_fh; print 'Enter login name: '; chomp(my $input = <STDIN>); print "Invalid!\n" unless exists $name{$input};
-- Ken
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: reading from file.
by Random_Walk (Prior) on Nov 14, 2013 at 01:37 UTC | |
by kcott (Archbishop) on Nov 14, 2013 at 07:12 UTC | |
by scripter87 (Novice) on Nov 14, 2013 at 10:46 UTC |