Perl - Multiple condition if statement without duplicating code?
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.
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!";
}
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} ) {