I am having some trouble trying to print from a file. Any ideas? Thanks
open(STDOUT,">/home/int420_101a05/shttpd/htdocs/receipt.html");
#Results of a sub-routine
&printReceipt;
close(STDOUT);
open(INF,"/home/int420_101a05/shttpd/htdocs/receipt.html"); $emailBody = <INF>;
close(INF);
print $emailBody;
ERRORS: Filehandle STDOUT reopened as INF only for input at ./test.c line 6.
print() on closed filehandle STDOUT at ./test.c line 9.
This discussion addresses the technical reason for the message. Relevant info from the thread is this:
From open(2) manpage:
When the call is successful, the file descriptor returned will be
the lowest file descriptor not currently open for the process.
So, to summarize, you closed STDOUT (file descriptor 1) and your file will be open as FD#1. That’s due to
open()'sproperties.As other have noted, the real reason you’re having this problem is that you should not use STDOUT for printing to a file unless there’s some special case where it’s required.
Instead, open a file for writing using a new file handle:
To print to filehandle from subroutine, just pass the file handle as a parameter.
The best way of doing so is to create an
IO::Fileobject and pass that object aroundmy $filehandle = IO::File->new(">$filename") || die "error: $!"; mySub($filehandle); sub mySub { my $fh = shift; print $fh "stuff" || die "could not print $!"; }You can also set a particular filehandle as a default filehandle to have print print to that by default using
selectbut that is a LOT more fragile and should be avoidded in favor of IO::File solution.