Chop
print "Please tell me your name: "; $name=<STDIN>; chop $name print "Thanks for making me happy, $name !\n"
and that fails with a syntax error. Can you spot why? Look at the error code, look at the
line number and see where the syntax is wrong. The answer is a missing semicolon
( ; ) on the end of the last two lines.
If you add a ; to the end of line 3, but not to the last line, then the
program works as it should. This is because Perl doesn't need a semicolon to end the last
statement of a block. However, I'd advise ending all your statements with semicolons
because you may well be adding more code to them and it is only one little keystroke.
When you add the semicolon(s), the program runs correctly. The chop
function removes the last character of whatever it is given to chop, in this
case removing the newline for us. In fact, that can be shortened:
print "Please tell me your name: "; chop ($name=<STDIN>); print "Thanks for making me happy, $name !";
The parentheses ( ) force chop to act on the result of what is inside them. So $name=<STDIN> is evaluated first, then the
result from that, which is $name , is chopped.
Try it without.
You can read from STDIN as much as you like. For your entertainment I have created a sophisticated multinational greeting machine:
print "Please tell me your name: ";
chop ($name=<STDIN>);
print "Please tell me your nationality: ";
chop ($nation=<STDIN>);
if ($nation eq "British" or $nation eq "New Zealand") {
print "Hallo $name, pleased to meet you!\n";
} elsif ($nation eq "Dutch" or $nation eq "Flemish") {
print "Hoi $name, hoe gaat het met u vandaag?!\n";
} else {
print "HELLO!!! SPEAKEEE ENGLIEESH???\n";
}
Aside from demonstrating the native English speaker's linguistic talents, this script
also introduces the or logical operator. We'll
cover or and its associates in more detail later
on. First, a word of warning.
Chopping is dangerous, as my friend One Hand Harold will tell you. Everyone is concerned about various forms of safety these days, and your perl code should be no exception.