CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
help with this code

 



redheards
New User

Nov 29, 2017, 7:41 PM

Post #1 of 3 (3128 views)
help with this code Can't Post

 
for (my $i = 0; $i <= 49; $i++) {
my @line = <$FH>;
my $counter = 0;
my $count = 0;
#print "$line\n";
my @array = split(/\s+/, $line[$count]);
$sum = $array[$count] + $sum;
if ($counter <= 10 ){
$counter = 0;
$count++;
}
$counter++;
}
I know there's most likely a better way to do this, but from this piece of my code isn't working. Im getting an error that my $line is not defined.


Laurent_R
Veteran / Moderator

Nov 30, 2017, 1:35 AM

Post #2 of 3 (3124 views)
Re: [redheards] help with this code [In reply to] Can't Post

Hi redheards,

there are numerous errors in your code (see below). It would be good it you explained what exactly you're trying to do, as it would make it easier for us to help you.


Code
my @line = <$FH>;


Unless you've shown only part of your code, you haven't opened a file yet, so the $FH filehandle is not defined. So you need to open the file first.

In addition, if $FH was properly defined, I very much doubt that you really want to slurp the whole content of the file into the @line array for each iteration of your for loop. Either you want to read only one line, and then you need to read the file in scalar context:


Code
my $line = <$FH>;

or you want the whole file to land into your array, in which case you should do that outside of the loop, i.e. before the for loop statement.

You don't have a $line variable anywhere, so it can't be defined.

The $count variable is refined within the loop and therefore reset at each iteration within the for loop, so that $line[$count] will always return the first line of the array, probably not what you want. Same problem with the $counter variable. Finally, you're never using the $i variable within the loop, so that's also likely to be an error compared to what you want.

Again, besides pointing to the errors, I can't help much further and tell you how to fix the issues, because I am not sure what you're trying to achieve. Please explain in plain English what your program is intended to do.


Laurent_R
Veteran / Moderator

Nov 30, 2017, 1:37 AM

Post #3 of 3 (3123 views)
Re: [redheards] help with this code [In reply to] Can't Post

One further and very basic piece of advice: always use the following pragmas:

Code
use strict; 
usa warnings;

in your programs. They will detect many of the errors you have in your code and help you fix them.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives