tags:

views:

111

answers:

3

I have a small piece of code for printing the contents in a text file like this,

use strict;
use warnings;

open (FILE, "2.txt") || die "$!\n";

my $var = <FILE>;
while ($var ne "")
{
    print "$var";
    $var = <FILE>;
} 

Text file is,

line 1
line 2
line 3 

After running the code i am getting a warning like this,

line 1
line 2
line 3
Use of uninitialized value $var in string ne at del.pl line 10, <FILE> line 3.

How to overcome this warning.

A: 

The quickest fix is probably to replace

while ($var ne "")

with

while (defined $var)
Sean
+8  A: 

The common idiom for reading from a file is this:

open my $fh, '<', $file or die $!;

while (defined(my $line = <$fh>)) {
    print $line, "\n";
}

Although the while loop implicitly tests for whether the result of the assignment is defined, it's better to do the test explicitly for clarity.

eugene y
Note that `while` normally tests for truth, not defined-ness. `while ($var = <FILE>)` is a special case where Perl adds an implicit `defined` test.
cjm
Please don't link to pirate copies of books
brian d foy
+4  A: 

I always use:

while(<FILE>) {
 print $_;
}

No such problems...

Paweł Dyda
This works fine for me... thx
Senthil kumar
This can lead to bugs, as `while` does not localize `$_`
eugene y

related questions