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 | |
|
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 | |
by ppp (Acolyte) on Jan 28, 2015 at 09:08 UTC | |
by soonix (Chancellor) on Jan 28, 2015 at 10:05 UTC | |
|
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 | |
|
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 |