Note that there are some explanatory texts on larger screens.

plurals
  1. POClarification on chomp
    primarykey
    data
    text
    <p>I'm on break from classes right now and decided to spend my time learning Perl. I'm working with Beginning Perl (<a href="http://www.perl.org/books/beginning-perl/" rel="nofollow">http://www.perl.org/books/beginning-perl/</a>) and I'm finishing up the exercises at the end of chapter three.</p> <p>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."</p> <p>Anyway, I had come up with this: </p> <pre><code>#!/usr/bin/perl use warnings; use strict; my %name_number= ( Me =&gt; "XXX XXX XXXX", Home =&gt; "YYY YYY YYYY", Emergency =&gt; "ZZZ ZZZ ZZZZ", Lookup =&gt; "411" ); print "Enter the name of who you want to call (Me, Home, Emergency, Lookup)", "\n"; my $input = &lt;STDIN&gt;; print "$input can be reached at $name_number{$input}\n"; </code></pre> <p>And it just wouldn't work. I kept getting this error message:</p> <blockquote> <p>Use of uninitialized value in concatenation (.) or string at hello.plx line 17, line 1</p> </blockquote> <p>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.</p> <p>The only difference between my code and the answer was the presence of <code>chomp ($input);</code> after <code>&lt;STDIN&gt;;</code>.</p> <p>Now, the author has used <code>chomp</code> in previous example but he didn't really cover what <code>chomp</code> was doing. So, I found this answer on www.perlmeme.org:</p> <blockquote> <p>The <code>chomp()</code> 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 <code>$/</code> (the input record separator), and <code>$/</code> defaults to a newline..</p> </blockquote> <hr> <p>Anyway, my questions are:</p> <ol> <li><p>What newlines are getting removed? Does Perl automatically append a <code>"\n"</code> to the input from <code>&lt;STDIN&gt;</code>? I'm just a little unclear because when I read "it actually removes any character that matches the current value of <code>$/</code>", I can't help but think "I don't remember putting a <code>$/</code> anywhere in my code."</p></li> <li><p>I'd like to develop best practices as soon as possible - is it best to always include <code>chomp</code> after <code>&lt;STDIN&gt;</code> or are there scenarios where it's unnecessary?</p></li> </ol>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload