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;
}
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.