我一直在研究一個cgi文件,該文件將檢查用戶是否想要註冊其憑據時是否已經使用了用戶名。如果使用用戶名,它應該通知他們,如果不是,則將其憑據保存到原始平面文件。我在比較foreach語句中賦予值的變量時遇到問題。如果用戶輸入的名稱與已存儲的名稱相同,我告訴foreach將用戶名分配給變量。我有它適當地分配變量,但後話我想告訴它在foreach之外再次比較這些變量,所以操作只能進行一次。這裏是我當前的代碼比較在foreach語句中分配的變量的問題
#!/usr/bin/perl
use warnings;
use strict;
use CGI qw(:standard);
use CGI::Carp qw/fatalsToBrowser warningsToBrowser/;
use Digest::MD5 qw(md5 md5_hex md5_base64);
#telling what variables are still to be used as global
our ($username, ,$user, $nametaken);
#assigning some local variables
my $username = param("username");
my $password = param("password");
my $hashpass = md5_hex($password);
print header, start_html();
#creating an array from the flatfile that usernames and passwords are stored
my @users = do { open my $fh, "<", "password.txt" or die $!; map { chomp; split /:/ } <$fh> };
#comparing the values in the array to the username entered
foreach my $user (@users) {
if ($user eq $username) {
#printing here to test if it is comparing correctly which it is
print p("$user\n");
#assigning the $user value to $nametaken so it can be compared to later
my $nametaken = $user;
#printing here to test if the variable was correctly assigned, which it is
print p("$nametaken\n");
}
}
#printing here to test if the variable was correctly assigned, which it is not printing
#so the foreach must be causing some king of issue for this variable after it is done and I don't know what that is
print p("$nametaken\n");
#Here is where I am trying to check if the username already exists and then save the user credentials if it does not
if ($nametaken eq $username) {
print p("Username already taken, Try again");
}
#As of now the else statement is running everytime and saving new user credentials even if a username is already taken
else {
open my $fh, ">>", "password.txt" or die $!;
print $fh "$username:$hashpass\n";
print p("Your account has been created sucessfully");
close $fh;
}
print end_html();
啊,我們的朋友,如果反模式。 – hobbs 2012-02-12 21:21:05
爲什麼使用'qw(...)'和'qw /.../',只需選擇一個。我實際上推薦使用'qw'...''或'qw「...」'來在StackOverflow上使用,因爲它更好地突出顯示。 – 2012-02-14 06:09:47