I am currently taking breaks from classes and decided to spend my time learning Perl. I work with Beginning Perl ( http://www.perl.org/books/beginning-perl/ ), and I finish the exercises at the end of the third chapter.
In one exercise, they told me: "Store important phone numbers in a hash. Write a program to search for numbers by person’s name."
Anyway, I came up with this:
#!/usr/bin/perl use warnings; use strict; my %name_number= ( Me => "XXX XXX XXXX", Home => "YYY YYY YYYY", Emergency => "ZZZ ZZZ ZZZZ", Lookup => "411" ); print "Enter the name of who you want to call (Me, Home, Emergency, Lookup)", "\n"; my $input = <STDIN>; print "$input can be reached at $name_number{$input}\n";
And that just won't work. I kept getting this error message:
Using uninitialized value in concatenation (.) Or string on hello.plx line 17, line 1
I tried to play a little with the code, but each “solution” looked more complex than the “solution” that appeared in front of it. Finally, I decided to check the answers.
The only difference between my code and the answer was chomp ($input); after <STDIN>; .
Now the author used chomp in the previous example, but he really did not talk about what chomp doing. So, I found this answer at www.perlmeme.org:
The chomp() function will remove (usually) any newline from the end of the line. The reason we usually say it is because it actually deletes any character that matches the current value of $/ (input record separator) and $/ defaults to a new line.
Anyway, my questions are:
What new lines are deleted? Does Perl automatically append "\n" to input from <STDIN> ? I am a bit unclear because when I read "it actually deletes any character that matches the current value of $/ " I cannot help but think "I don’t remember to put $/ anywhere in my code."
I would like to develop best practices as soon as possible - is it always better to include chomp after <STDIN> or are there scripts where this is not necessary?
krebshack
source share