I'm on break from classes right now and decided to spend my time learning Perl. I'm working with Beginning Perl (http://www.perl.org/books/beginning-perl/) and I'm finishing up the exercises at the end of chapter three.
One of the exercises asked that I "Store your important phone numbers in a hash. Write a program to look up numbers by the person's name."
Anyway, I had come 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 it just wouldn't work. I kept getting this error message:
Use of uninitialized value in concatenation (.) or string at hello.plx line 17, line 1
I tried playing around with the code some more but each "solution" looked more complex than the "solution" that came before it. Finally, I decided to check the answers.
The only difference between my code and the answer was the presence of chomp ($input);
after <STDIN>;
.
Now, the author has used chomp
in previous example but he didn't really cover what chomp
was doing. So, I found this answer on www.perlmeme.org:
The
chomp()
function will remove (usually) any newline character from the end of a string. The reason we say usually is that it actually removes any character that matches the current value of$/
(the input record separator), and$/
defaults to a newline..
Anyway, my questions are:
What newlines are getting removed? Does Perl automatically append a
"\n"
to the input from<STDIN>
? I'm just a little unclear because when I read "it actually removes any character that matches the current value of$/
", I can't help but think "I don't remember putting a$/
anywhere in my code."I'd like to develop best practices as soon as possible - is it best to always include
chomp
after<STDIN>
or are there scenarios where it's unnecessary?