tags:

views:

72

answers:

3

Why will my script now work correctly?

I follow a YouTube video and worked for the guy.

I am running Perl on Windows using ActiveState ActivePerl 5.12.2.1202

Here is my tiny tiny code block.

print "What is your name?\n";
$name = <STDIN>;
if ($name eq "Jon") {
print "We have met before!\n";
} else {
print "We have not met before.\n";
}

The code automatically jumps to the else statement and does not even check the if statement.

+1  A: 

When you read the name standard input as $name = <STDIN>;

$name will have a trailing newline. So if I enter foo , $name will actually have foo\n.

To get rid of this newline you an make use of the chomp function as:

chomp($name = <STDIN>);
codaddict
+11  A: 

The statement $name = <STDIN>; reads from standard input and includes the terminating newline character "\n". Remove this character using the chomp function:

print "What is your name?\n";
$name = <STDIN>;
chomp($name);
if ($name eq "Jon") {
  print "We have met before!\n";
} else {
  print "We have not met before.\n";
}
Richard Cook
Perfect answer, thank you.
Solignis
+2  A: 

The trick in programming is to know what your data are. When something's not acting like you expect, look at the data to see if they are what you expect. For instance:

 print "The name is [$name]\n";

You put the braces around it so you can see any extra whitespace that might be there. In this case, you would have seen:

The name is [Jon
]

That's your clue that there is extra stuff. Since the eq has to match exactly, it fails to match.

If you're just starting with Perl, try Learning Perl. It's much better than random videos from YouTube. :)

brian d foy
I will have to find that book, I already bought Perl for Dummies and Beginning Perl by Wrox press.
Solignis
Don't use either of those. Not only are they ancient, but they are not a good way to learn Perl. If you want Beginning Perl, get the latest version from Apress, not the one from Wrox.
brian d foy
Shoot I already purchased it and it is being shipped. Oh well, so you are saying Apress makes a better version that is newer?
Solignis
Yes, the latest Apress version is by definition newer. It's also better. As general advice, don't buy old computer books. Buy the most recent ones. Not only should they cover more of the recent features, but good authors fix problems people found in the earlier versions.
brian d foy
And, there is a list of good Perl books in the current perlfaq2 (and the future perlbook).
brian d foy