-2

Having a problem with if statement in Perl, my if statement is not working. What am I doing wrong, because I'm using strict and warnings module, but still my if statement is not working.

#!/usr/bin/env perl

use strict;
use warnings;


sub Granted
{
    print "\n\nAccess Granted\n\n";
}


sub Access
{
    print "\n\n\n\n";
    sleep 1;
    print "Enter your name: ";
    my $name = <STDIN>;
    sleep 1;

    if ("$name" eq "jake")
    {
        Granted
    }

}

Access 
  • 1
    There's no reason to use `"$name"`. Just use `$name`. But you have to trim the newline at the end of `$name` before you do the comparison. – David Hammen Feb 28 '16 at 16:15
  • Although it's valid like you wrote it (by accident, I guess), please call your subroutines like this: `Granted();`, i.e. with parens `()` and a final `;`. The `;` _may_ be omitted after the last statement in a block (like you do), but it's ugly. – PerlDuck Feb 28 '16 at 16:29
  • 1
    When in doubt: `use Data::Dumper; $Data::Dumper::Useqq=1; print Dumper $name;` – TLP Feb 28 '16 at 17:10

1 Answers1

2

You've misdiagnosed the problem. The if is fine, the problem is the data you are comparing to the input.

When you read from a file handle, you include the record separator character (by default that is a new line).

You are comparing "jake\n" to "jake".

See also chomp.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335