In an effort to learn Perl I was going through the Llama book. When I came to the second chapter there was an exercise where we need to enter two numbers and the program will return their product. I did the program and it worked well except for a small glitch. Here is my code and the output.
print "Enter the first number : ";
$num1 = <STDIN>;
print "Enter the second number : " ;
$num2 = <STDIN>;
$prd = $num1 * $num2;
print "The product of $num1 and $num2 is $prd\n";
The code worked well and outputted 20 if we enter 4 and 5 but it printed output like this.
Enter the first number : 4
Enter the second number : 5
The product of 4
Now it was annoying. Having only started programming in Perl and my previous experience in C or Java or even PHP never made me expect something like this. I expected it to print the whole sentence in one single line. What could be wrong. Then I recalled Llama telling about <STDIN> adding a ‘\n’ to the input and the need for using chomp() to get rid of this.
So I modified code and added two more lines
This made it correct. But still I found it odd and thought this feature of <STDIN> a nuisance. So I went into some knowledge hunting. I asked in #perl channel at freenode. So far I was wary and wasn’t talking and was merely listening. I was afraid even while asking this of getting some serious ‘RTFM’. But the folk in there responded nicely. Thanks for <claes_>. He gave the apt reply. Here is what I learned from him.
There is a special variable in Perl named $/ which is initialzed to be ‘\n’. This variable is termed the input record separator. This variable is used to separate the various lines from your inut. Since $/ contains ‘\n’ it assumes your input has been ended once you key in the return key.(Note: Though the ‘\n’ is not a part of the intended input, since you entered it it will also be included as a part of your input). That’s why we get the newline when printing it back. When we use chomp() it removes these ‘\n’. If we explicitly assign say, ‘f’ to $/ then <STDIN> enters whatever up to the first ‘f’ it sees. Also the functionality of chomp() changes. It will now remove the last ‘f’ from your input (Once again though ‘f’ wasn’t in your intended input, since you entered it it would be there, Please don’t do so. Leave ‘$/’ to the ‘/n’, or be ready to bear the dire after effects). So $/ variable helps in entering user input from standard input.
Another option is to use in the above example is the chop() method [I earlier called it a better option, but I taking that away as per the info by 'Andrew']. When chomp() removes whatever declared in the $/ variable, chop() removes the last character from the input.
So in the below snippet
$str = "Christy;
the output is ‘Christ';
I think I was successful in explaining the issue and let this save another newbie someday.
[Revision: Thursday 3 Sep, 2009, There was some confusion in the explanation of input record separator. Thank to Chas Owen. I corrected it.}