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 http://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
chompafter<STDIN>or are there scenarios where it’s unnecessary?
<STDIN>reads to the end of the input string, which contains a newline if you press return to enter it, which you probably do.chompremoves the newline at the end of a string.$/is a variable (as you found, defaulting to newline) that you probably don’t have to worry about; it just tells perl what the ‘input record separator’ is, which I’m assuming means it defines how far<FILEHANDLE>reads. You can pretty much forget about it for now, it seems like an advanced topic. Just pretendchompchomps off a trailing newline. Honestly, I’ve never even heard of$/before.As for your other question, it is generally cleaner to always chomp variables and add newlines as needed later, because you don’t always know if a variable has a newline or not; by always chomping variables you always get the same behavior. There are scenarios where it is unnecessary, but if you’re not sure it can’t hurt to
chompit.Hope this helps!