Senthil kumar
Senthil kumar

Reputation: 993

How can I avoid warnings in Perl?

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.

Upvotes: 1

Views: 344

Answers (3)

Eugene Yarmash
Eugene Yarmash

Reputation: 149796

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.

Upvotes: 8

Paweł Dyda
Paweł Dyda

Reputation: 18662

I always use:

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

No such problems...

Upvotes: 3

Sean
Sean

Reputation: 29772

The quickest fix is probably to replace

while ($var ne "")

with

while (defined $var)

Upvotes: 0

Related Questions