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

Hi....I do not understand why my File handle is closed. can you tell me? and also maybe how I can fix it? Thanks,
#!/usr/bin/perl -w use strict; my $agent = "best1agent_start"; my $collect = '/usr/bin/su - patrol /usr/adm/best1_default/bgs/scripts +/best1collect -q>>$LOG 2>>$LOG'; my $cf_dir = "/root/sysedge/cf_files"; open SH_FILES, "sh.file" or die "Error: $!"; my @sh_f=<SH_FILES>; close SH_FILES; foreach my $sh(@sh_f){ chomp $sh; open(OUT, "/tmp/$sh".".sysedge.sh"); my $line; open (SH, "$cf_dir/$sh") or die "ERROR $!"; while ($line = <SH>){ if($line =~ /$agent/){ $line = $collect; print OUT $line; } print OUT $line; } }

Replies are listed 'Best First'.
Re: print() on closed filehandle OUT at B.p line 19, <SH> line 1732.
by hipowls (Curate) on Feb 24, 2008 at 03:31 UTC

    Change open OUT to this

    open(OUT, "/tmp/$sh".".sysedge.sh") or die "Can't open /tmp/$sh.sysedg +e.sh: $!\n";
    and perl will tell you

    Update: kudos to wjc75019 for spotting his error without my help;-) But the or die is still good advice

      Duhhh...Thanks! I forgot to put in >
      Nitpick:

      Those die statements works "better" without an explicit newline.

      my $file = '/nowhere/to/be/seen'; open my $fh1, $file or warn "$file: $!\n"; open my $fh2, $file or warn "$file: $!";
        No way! There are error messages intended for developers, and there are error messages intended for users. IO errors are clearly the latter, and line numbers are meaningless to the user. If you need the line number to make this error message meaningful, you have a bad error message.
Re: print() on closed filehandle OUT at B.p line 19, <SH> line 1732.
by jwkrahn (Abbot) on Feb 24, 2008 at 03:46 UTC
    open(OUT, "/tmp/$sh".".sysedge.sh");

    You are opening the file for READ ONLY INPUT and then are try to print out to that filehandle.    You need to either use output or append mode to be able to print out on that filehandle.

Re: print() on closed filehandle OUT at B.p line 19, <SH> line 1732.
by olus (Curate) on Feb 24, 2008 at 20:41 UTC

    I'm in doubt whether you are familiar with the quote below. In either case, I believe a good practice would be to close the file handles when they are no longer needed. And it would be better to do it yourself than someone else at a latter stage when doing maintenance or applying patches.

    You don't have to close FILEHANDLE if you are immediately going to do another open on it, because open will close it for you. (See open.) However, an explicit close on an input file resets the line counter ($. ), while the implicit close done by open does not.

    Though re-opening on the same file handle closes it, you are also not closing SH and OUT after the foreach loop. perl will close it for you when the script ends but still, you should explicitly close them in your code.