in reply to How to handle the error when we try to read an empty text file in perl

Hello ppp,
i think your assumption is wrong: Perl does not complain for an empty file
use strict; use warnings; open my $fh, '<', 'C:\scripts\vacuum.txt', or die "Could not open file + $!"; while (my $line = <$fh>) { print "line $. reading '$line'\n"; } #update: removed nonsense part as pointed by BrowserUk below

You must have some other issue like permission, path or other.

Anyway you can test the size of a file with file test operators:
-e File exists. -z File has zero size (is empty). -s File has nonzero size (returns size in bytes). >perl -we "use strict; my $file = 'c:\scripts\vacuum.txt'; if (-e -s $ +file){print qq(it exists and has not zero lenght\n)} else {print qq(e +xists but zero lenght\n)}" exists but zero lenght >perl -we "use strict; my $file = 'c:\scripts\002.txt'; if (-e -s $fil +e){print qq(it exists and has not z ero lenght\n)} else {print qq(exists but zero lenght\n)}" it exists and has not zero lenght
Also see sysopen to have a more granular approach opening files

HtH
L*
There are no rules, there are no thumbs..
Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

Replies are listed 'Best First'.
Re^2: How to handle the error when we try to read an empty text file in perl
by ppp (Acolyte) on Jan 28, 2015 at 09:08 UTC
    Hii thansk for answer plese see the updated question.
      I mean if file is empty then it should add the $address in ppp.txt's first line otherwise go to the while loop
      in this case, rewording and expanding Discipulus' example:
      my $file = 'C:\ppp.txt'; print "file '$file' "; if (-e $file) { print 'exists '; if (-z $file) { print 'but is empty'; } else { print 'and is not empty'; } } else { print q!doesn't exist!; } print "\n";
      you would have to move your code in like this (untested):
      my $file = 'C:/ppp.txt'; print "file '$file' "; if (-e $file) { print 'exists '; if (-z $file) { # print 'but is empty'; my $fh, '>>', $file, or die "Could not open file '$file' for +appending: $!"; print$fh $address . ' or whatever you want'; close $fh; } else { # print 'and is not empty'; ... (your "old" open and while loop) } } else { # print q!doesn't exist!; ... (either create it or print error message) } print "\n";