Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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

(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} ) {
                @Rob: perhaps you don't enable warnings (which you certainly should do).  even better is making warnings fatal.
– ysth
                Dec 7, 2014 at 3:50

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!";
                Well, actually I was hardcoding passwords. It wasn't for anything important, just a project.
– John Doe
                Mar 30, 2015 at 3:07
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.