Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Below are a few tips to make your code more idiomatic:</p> <ul> <li>The <a href="http://perldoc.perl.org/perlvar.html#%24INPUT_LINE_NUMBER" rel="nofollow noreferrer">special variable <code>$.</code></a> already holds the current line number, so you can likely get rid of <code>$lctr</code>.</li> <li>Are empty lines really errors, or can you ignore them?</li> <li>Pull apart the list returned from <code>split</code> and give the pieces names.</li> <li>Let Perl do the opening with the <a href="http://perldoc.perl.org/perlop.html#I/O-Operators" rel="nofollow noreferrer">"diamond operator"</a>:</li> </ul> <blockquote> <p>The null filehandle <code>&lt;&gt;</code> is special: it can be used to emulate the behavior of <code>sed</code> and <code>awk</code>. Input from <code>&lt;&gt;</code> comes either from standard input, or from each file listed on the command line. Here's how it works: the first time <code>&lt;&gt;</code> is evaluated, the <code>@ARGV</code> array is checked, and if it is empty, <code>$ARGV[0]</code> is set to <code>"-"</code>, which when opened gives you standard input. The <code>@ARGV</code> array is then processed as a list of filenames. The loop</p> <pre><code>while (&lt;&gt;) { ... # code for each line } </code></pre> <p>is equivalent to the following Perl-like pseudo code:</p> <pre><code>unshift(@ARGV, '-') unless @ARGV; while ($ARGV = shift) { open(ARGV, $ARGV); while (&lt;ARGV&gt;) { ... # code for each line } } </code></pre> <p>except that it isn't so cumbersome to say, and will actually work.</p> </blockquote> <p>Say your input is in a file named <code>input</code> and contains</p> <pre>Campbell's soup,0.50 Mac & Cheese,0.25</pre> <p>Then with</p> <pre><code>#! /usr/bin/perl use warnings; use strict; die "Usage: $0 coupon-file\n" unless @ARGV == 1; while (&lt;&gt;) { chomp; my($product,$discount) = split /,/; next unless defined $product &amp;&amp; defined $discount; print "$product =&gt; $discount\n"; } </code></pre> <p>that we run as below on Unix:</p> <pre>$ ./coupons input Campbell's soup => 0.50 Mac & Cheese => 0.25</pre>
 

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