Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your program is reasonably close to working. With these changes it will do exactly what you want</p> <ul> <li><p><em>Always</em> use <code>use strict</code> and <code>use warnings</code> at the start of your program, and declare all of your variables using <code>my</code>. That will help you by finding many simple errors that you may otherwise overlook</p></li> <li><p>Use lexical file handles, the three-parameter form of <code>open</code>, and <em>always</em> check the return status of any <code>open</code> call</p></li> <li><p>Declare the <code>$total</code> variable outside the loop. Declaring it inside the loop means it will be created and destroyed each time around the loop and it won't be able to accumulate a total</p></li> <li><p>Declare a <code>$count</code> variable in the same way. You will need it to calculate the average</p></li> <li><p>Using <code>while (FILE) {...}</code> just tests that <code>FILE</code> is true. You need to read from it instead, so you must use the <code>readline</code> operator like <code>&lt;FILE&gt;</code></p></li> <li><p>You want the <em>default</em> call to <code>split</code> (without any parameters) which will return all the non-space fields in <code>$_</code> as a list</p></li> <li><p>You need to add a variable in the assignment to allow for athe <code>AM</code> or <code>PM</code> field in each line</p></li> </ul> <p>Here is a modification of your code that works fine</p> <pre><code>use strict; use warnings; open my $fh, '&lt;', "files.txt" or die $!; my $total = 0; my $count = 0; while (&lt;$fh&gt;) { my ($date, $time, $ampm, $numbers, $type) = split; $total += $numbers; $count += 1; } print "The total is $total\n"; print "The count is $count\n"; print "The average is ", $total / $count, "\n"; </code></pre> <p><strong>output</strong></p> <pre><code>The total is 124533 The count is 3 The average is 41511 </code></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