Help with PERL loop

I wrote a script to list all lines in a file with Perl. I am having trouble with the looping part of it. My script is supposed to look at the file and as long as the file is larger than the current line it prints a new line.

I am getting an error that won't stop on the while line of my code I believe.
Here is the code:

[highlight=perl]#!/usr/bin/perl -w
unless(scalar(@ARGV)==1){
print "error: incorrect number of arguments",
"\n",
"usage: linenum.pl [filename]",
"\n";
exit 1;
}

# Open function used with filehandle and input file.
open(MY_FILE, "$ARGV[0]") or die
"error: argument must be a file\n",
"usage: linenum.pl [filename]\n$!\n";

# Check if file is a directory
if (!-f "$ARGV[0]"){
print "error: argument must be a file",
"\n",
"usage: linenum.pl [filename]\n";
exit 1;
}

$COUNTER=1; # Used for printing line numbers

# Loop and write lines from
while($LINE <= <MY_FILE>){
# Adds leading zeros for numbers 1 digit long
if ($COUNTER<10){
print "000";
}
# Adds leading zeros for numbers 2 digits long
if (($COUNTER>9) && ($COUNTER<100)){
print "00";
}
# Adds leading zeros for numbers 3 digits long
if (($COUNTER>99) && ($COUNTER<1000)){
print "0";
}
# Prints line number and line
print "$COUNTER: $LINE";
$COUNTER+=1;
}

exit 0;
[/highlight]

Please post your error message, thanks.

Also, have you tried invoking Perl with the -d switch? Then, your program will be run inside the Perl debugger.

I tried to post my screen but i guess it was denied.

Here is the error and it just goes on and on I have to close down to end it.

Use of uninitialized value in numeric le (<=) at ./linenum.pl line 26, <MY_FILE> line 29

Use of uninitialized value in concatatenation (.) or string at ./linenum.pl line 40, <MY_FILE> line 29.

(a) You haven't declared or assigned $LINE, and
(b) You are trying to compare, rather than assign the next line in the while loop.

That makes Perl go into an infinite loop.

The correct method is either this (fetch next line and test for truthfulness) -

...
while (<MY_FILE>) {
...

or this (fetch next line, assign to $LINE and test for truthfulness) -

...
while ($LINE = <MY_FILE>) {
...

tyler_durden

One suggestion for future reference: adding

use strict;

to your scripts will save you a lot of debugging time in the future.

The error (actually warning) messages you posted are the result of your '-w' flag, and tell you that you should look at lines 26 and 40 for an uninitialized value.

What is that value? It's $LINE. $LINE is never initialized, so the while() loop will never stop.

Line 26 (the first line of the while() loop) doesn't do what you think it does. Rather than attempting to do a numeric comparison (<=), try initializing $LINE with a simple assignment:

while ( $LINE = <MY_FILE> ) {

This will set $LINE to each line of the file in turn, and then the rest of the loop code will execute with that value.