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

Hi monks,
I am showing a sample part of my coding where I am finding a problem.
I used three argument open for opening files. I wrote some contents in a file test.txt as shown below.
After that I copied the same file with another name test1.txt and I did some replacements. But when I printed the output I didn't got any output in my console.
But when I added close function it was working fine.
AFAIK close function is not mandatory in Perl (that too in three arguments it ll close the handle automatically). Also for safer purpose I used three arguments open function as well.
What is going on here or am I missing something? While writing some data in file, won't it write in file? or will it have the output only in buffer in this scenario?
If it is a silly question or mistake, I apologise for that, because I tested the below code many times but not getting output.

use strict; use warnings; use File::Copy; open (my $dbout_h, '>', "D:\\Projects\\test.txt") || die ("Unable to o +pen/File not exists: $dboutfile\n"); #open file to write print $dbout_h "<html><b>output - Table:</b><hr>\n<table border=2>\n"; my @arr =( 1, 2, 3); { local $" = '</td><td>'; for (@arr) { next if (!@arr); print $dbout_h "<tr><td>@arr</td></tr>\n"; #print the resul +ts in database output file } } print $dbout_h "<\/table>\n<\/html>"; close ($dbout_h); copy ( "D:\\Projects\\test.txt", "D:\\Projects\\test1.txt"); open (my $dbout1_h, '<', "D:\\Projects\\test1.txt") || die ("Unable to + open/File not exists: test1.txt\n"); #open file to write my $file = do {local $/, <$dbout1_h>}; $file =~ s!<table!<tab!g; $file =~ s!</table!</tab!g; print $file;

Thanks in advance

Prasad

Replies are listed 'Best First'.
Re: Question on Filehandle: close function
by Fletch (Bishop) on Apr 17, 2007 at 15:08 UTC

    Lexical filehandles (what you get when you use open( my $fh, $mode, $path )) will automatically close the handle for you when the handle goes out of scope. Since $dbout_h in your example code is still in scope through the end of the file it's still a valid handle and wouldn't be automatically closed (and the buffers flushed). When you add the explicit close the buffers were flushed and you saw the contents.

    Even using lexical filehandles (or as my habit since I've been working on older Perls, localized globs) I tend to put the explicit close. That way it's explicit where I expect the filehandle to become invalid and what not.