1

New to Perl. Using Windows 10 w/ Padre IDE. I have a question that has been stumping me and it's probably very simple yet I have yet to find an answer on the net.

Here is the code that is working up until my search. It reads a list.txt file with names and matching phone numbers so I have two hashes (one is name => number, the second is number =>).

my $search = "";

print "File name to be read in: ";
my $textFile = <>;

open FILE, $textFile;
my %hash;

while (<FILE>)
{
    chomp;
    my ($key, $val) = split / /;

    $hash{$key} .= exists $hash{$key} ? "$val" : $val;
}

close FILE;

open FILE, $textFile;
my %hash2;

while (<FILE>)
{
    chomp;
    my ($val, $key) = split / /;

    $hash2{$key} .= exists $hash2{$key} ? "$val" : $val;
}

close FILE;


print "(N) for name (#) for number search and (.) to exit: ";

$search = <>;

if ($search == "N")                #heres where we have the problem
{
        print "Enter name: ";  
        my $person = <>;           #user defined search looks for Bob Smith
        print $hash{$person};      #prints nothing
}

However, when I make the search non-user defined, it works perfected as in:

if ($search == "N")                
{
        #print "Enter name: ";  
        #my $person = <>;           
        print $hash{"Bob Smith"};      #prints Bob Smith's number
}

For the record, I had $search print to screen to verify that there was no issue whenI entered the name in the first place. When I user-define the search, the hash will not pull up. When the name is specically coded into the hash function, it works every time.

Thank you for helping a stumped Perl Noobie.

toolic
  • 57,801
  • 17
  • 75
  • 117
jveytech
  • 13
  • 4

1 Answers1

2

You have a trailing newline character. You need to chomp before you compare:

$search = <>;
chomp $search;

Also, you should use the string compare eq:

if ($search eq "N")
toolic
  • 57,801
  • 17
  • 75
  • 117