ppp has asked for the wisdom of the Perl Monks concerning the following question:

I am a perl beginner and under a situation where i have written a script and i am trying to read a text file to do check if $address exist in the file(see in my code) through the perl script and my code to so this is written below :

open my $fh, '<', 'C:\ppp.txt', or die "Could not open file $!"; while (my $line = <$fh>) { foreach my $str ($line) { if (index($line, $address) != -1) { $counter++; $flag='1'; } } }

Where is the problem ? The problem is when i try to read a file which is empty then it gives error(because in my code i see at each line that does this $address exist in that line. If it exist then i return the flag=1 and if not then i return flag=0. The code gives error that could not open file at line(open my $fh, '<', 'C:\ppp.txt', or die "Could not open file $!";)it ONLY HAPPENS when file is empty (i mean when there is no string to compare $address in text file) and IT WORKS FINELY when there IS ATLEAST ONE string written to do comparison with $address. I have verified it and it means there is no read write problems. If it was a c++ code then i would have done something like this :

open my $fh, '<', 'C:\ppp.txt', or die "Could not open file $!"; if ($fh contains an empty file) { // then add this the $address in the ppp.txt's first line }

I mean if file is empty then it should add the $address in ppp.txt's first line otherwise go to the while loop and compare if the existing address in text file does match with $address or not and return flag=1 if it does?(which my while loop already do) How to do it in perl ?

Replies are listed 'Best First'.
Re: How to handle the error when we try to read an empty text file in perl
by BrowserUk (Patriarch) on Jan 28, 2015 at 08:02 UTC
    The problem is when i try to read a file which is empty then it crashes (because the code try to read a file and it find nothing in the first line and code breaks with an error that couldnt open this file).

    That makes no sense. If the file is empty the while loop will never be entered:

    E:\test>dir Volume in drive E is New Volume Volume Serial Number is 1821-B83A Directory of E:\test 28/01/2015 08:10 <DIR> . 28/01/2015 08:10 <DIR> .. 28/01/2015 08:10 0 fred 1 File(s) 0 bytes 2 Dir(s) 1,624,181,088,256 bytes free E:\test>perl -E"while( <> ){ print 'got here'; }" fred

    BTW, this is also nonsense:

    open my $fh, '<', 'C:\ppp.txt', or die "Could not open file $!"; while (my $line = <$fh>) { foreach my $str ($line)

    Iterating a foreach over a single scalar variable, means it will only ever iterate once. Ie. it is completely redundant.


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". I'm with torvalds on this
    In the absence of evidence, opinion is indistinguishable from prejudice. Agile (and TDD) debunked
Re: How to handle the error when we try to read an empty text file in perl
by Discipulus (Canon) on Jan 28, 2015 at 07:52 UTC
    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.
      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";
Re: How to handle the error when we try to read an empty text file in perl
by Discipulus (Canon) on Jan 28, 2015 at 10:10 UTC
    If it was a c++ code then i would have done something like this : open my $fh, '<', 'C:\ppp.txt', or die "Could not open file $!"; if ($fh contains an empty file) { // then add this the $address in the ppp.txt's first line }
    This is easy in Perl:
    my $file = 'c:\ppp.txt'; if (-e -z $file) { warn "$file exists but is zero sized!\n"; open my $tmp, '>', $file or die "cannot write to $file!\n"; # #write what you need to close $tmp }
    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.
Re: How to handle the error when we try to read an empty text file in perl
by Anonymous Monk on Jan 28, 2015 at 07:53 UTC

    I am a perl beginner ... Where is the problem? ... then it crashes ...

    Hi ppp,

    What does "it crashes" mean?

    Please use copy/paste to answer this question