Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!";
}
like image 866
John Doe Avatar asked Feb 13 '14 15:02

John Doe


3 Answers

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.

like image 191
Axeman Avatar answered Oct 08 '22 09:10

Axeman


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} ) {
like image 28
ysth Avatar answered Oct 08 '22 08:10

ysth


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!";
}
like image 2
Dodger Avatar answered Oct 08 '22 08:10

Dodger