我遇到了一种情况,我需要从名为 login.txt(在当前目录中)的文件中读取 2 行数据(用户名和密码)。读取后,用户名(第一行)必须存储在 $user 中,第二行(密码)必须存储在 $pass 中。
如果找不到该文件,我必须提示用户输入用户名和密码并将其存储在 $user 和 $pass 并创建文件 login.txt(在当前目录中)并将这两行写入文件.
my $user;
my $pass;
my $login = "login.txt";
unless (-e $login) {
print "Entering first time execution mode....!\n";
sleep(2);
print "Enter username:\n";
$user = <STDIN>;
chomp($user);
print "Enter password:\n";
$pass = <STDIN>;
chomp($pass);
unless(open LINFO, '>'.$login) {
# Die with error message
# if we can't open it.
die "\nUnable to create $login\n";
}
print LINFO "$user\n";
print LINFO "$pass\n";
close LINFO;
}
if (-e $login) {
open (LINFO, '$login') or die "Cant open\n";
while( my $line = <LINFO>) {
print $line;
chomp($line);
if ($. == 1) { $user = $line; }
elsif ($. == 2) { $pass = $line; }
last if $. == 2;
}
close LINFO;
}
print $pass;
print $user;
当文件不存在时,一切正常(甚至打印 $user 和 $pass),但会收到如下错误消息:-
readline() on closed filehandle LINFO at loginfile.pl line 43.
如果文件已经存在,那么我会收到以下错误
readline() on closed filehandle LINFO at loginfile.pl line 43.
Use of uninitialized value $pass in print at loginfile.pl line 59.
Use of uninitialized value $user in print at loginfile.pl line 60.
不知道这里有什么问题