[perl] Perl - Multiple condition if statement without duplicating code?

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!";
}

This question is related to perl if-statement

The answer is


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!";
}