This is a Perl program, run using a terminal (Windows Command Line). I am trying to create an "if this and this is true, or this and this is true" if statement using the same block of code for both conditions without having to repeat the code.
if ($name eq "tom" and $password eq "123!") elsif ($name eq "frank" and $password eq "321!") {
print "You have gained access.";
}
else {
print "Access denied!";
}
I don't recommend storing passwords in a script, but this is a way to what you indicate:
use 5.010;
my %user_table = ( tom => '123!', frank => '321!' );
say ( $user_table{ $name } eq $password ? 'You have gained access.'
: 'Access denied!'
);
Any time you want to enforce an association like this, it's a good idea to think of a table, and the most common form of table in Perl is the hash.
Simple:
if ( $name eq 'tom' && $password eq '123!'
|| $name eq 'frank' && $password eq '321!'
) {
(use the high-precedence &&
and ||
in expressions, reserving and
and or
for flow control, to avoid common precedence errors)
Better:
my %password = (
'tom' => '123!',
'frank' => '321!',
);
if ( exists $password{$name} && $password eq $password{$name} ) {
if ( ($name eq "tom" and $password eq "123!")
or ($name eq "frank" and $password eq "321!")) {
print "You have gained access.";
}
else {
print "Access denied!";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With