Fixing an error from using Loop to read a file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Donnie Seibel
    New Member
    • Oct 2010
    • 7

    Fixing an error from using Loop to read a file

    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:

    Code:
    #!/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;
    This is the error and I can't figure out what it means.

    "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."

    This error doesn't stop either I have to close my program to end it.
  • RonB
    Recognized Expert Contributor
    • Jun 2009
    • 589

    #2
    Your script has a number of problems, but lets start with this:

    change line 26 ti this:
    Code:
    while( my $LINE = <MY_FILE> ){

    Comment

    Working...