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

In the below code, I am trying to read directory and put all directory names into the text file. Here's a catch. When I try to count and read lines in the generated text file it's not working. But, if I try to parse a text file which is having such information it's working. Please help me to understand where it's going wrong.

use strict; use warnings; use Cwd; my $cwd = getcwd(); #inputs# my $dir = "D:\\Temp"; my $fff; my @dir = (); my $contilog = "$cwd"."\\input.txt"; open(LOG,">",$contilog) || die "Cannot create log file ...."; opendir (DIR,$dir); @dir=readdir(DIR); closedir(DIR); @dir = sort(@dir); foreach $fff (@dir){ write_log("$fff"); }

here my code is not working

my $input = "$contilog";

If I uncommment below line and run its working

#my $input = "$cwd"."\\input1.txt";
open my $fh, '<', $input or die "unable to open file: $!"; # read it line by line with while, using the $. variable to # show the line number (instead of your own counter). while( <$fh> ) { print "$_\n"; # LINE NO: LINE } print "$contilog\n"; print "$input\n"; print "Total lines was $.\n"; sub write_log{ print LOG @_; print LOG "\n"; } sub trim($) { my $string = shift; $string =~ s/^\s+//; $string =~ s/\s+$//; return $string; }

Replies are listed 'Best First'.
Re: Problem with reading generated text file
by hippo (Archbishop) on Mar 15, 2020 at 16:33 UTC

    If I have understood your code correctly you are attempting to open the same file twice within the same code (once for writing and once for reading) to different filehandles. One of the filehandles is a bareword and the other is a scalar (why?). You neither close nor flush the writing filehandle before opening the reading one. It is therefore not surprising that you have problems.

    If we remove the MSWin specific stuff, we can show a simple, working example like this.

    #!/usr/bin/env perl use strict; use warnings; use autodie; use IO::Handle; open my $fh, '+>', 'foo.txt'; print $fh "foo\nbar\nbaz\n"; $fh->flush; seek $fh, 0, 0; while (<$fh>) { print "Read: $_"; } close $fh;

    There's only one filehandle, one open and IO::Handle allows us to flush it on demand.

      Yeah, Thanks. I missed a simple logic I Just added below code before text file open again and it's working again

      CLOSE(LOG);