ユーザーが資格情報を登録したいときにユーザー名が既に使用されているかどうかをチェックするcgiファイルを作成しています。ユーザー名が取得された場合は、通知することになっています。そうでなければ、元のフラットファイルに資格情報を保存します。私はforeachステートメント内で値を割り当てた変数を比較するのに問題があります。ユーザーが入力した名前と既に格納されている名前が同じ場合、変数にユーザー名を割り当てるようにforeachに指示します。私は変数を適切に割り当てていますが、単語の後には、foreachの外でこれらの変数を再度比較するように指示したいので、操作は1回だけ実行されます。ここに私の現在のコード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();
私たちの友人、For-If Antipattern。 – hobbs
なぜあなたは 'qw(...)'と 'qw /.../'を使用していますか? StackOverflowでの使用のために、実際には 'qw '...''、または 'qw" ... "'が推奨されます。 –