Open Perl file problem
I am having trouble trying to print from a file. Any ideas? Thanks to
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.
source to share
-
This discussion addresses the technical reason for the message . The relevant information from the stream is as follows:
From the open (2) manpage:
When the call is successful, the file descriptor returned will be the lowest file descriptor not currently open to the process.
But STDOUT still applies to filehandle # 1. This warning might be helpful. While it could be argued that further use of STDOUT as an output filehandle raises a warning as well ...
So, to summarize, you closed STDOUT (file descriptor 1) and your file will open as FD # 1. This is because of properties
open()'s
. -
As others have pointed out, the real reason you're having this problem is because you shouldn't use STDOUT to print to a file unless there is a special case where it needs to be.
Instead, open the file for writing with a new file descriptor:
open (OUTFILE, "> / home / int420_101a05 / shttpd / htdocs / receipt.html") || die "Could not open: $!"; print OUTFILE "data"; close (OUTFILE);
-
To print to a file descriptor from a subroutine, simply pass the file descriptor as a parameter .
The best way to do it is to create an object
IO::File
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 specific file descriptor as the default file descriptor for printing by default using
select
but this LOT is more fragile and should be reserved in favor of the IO :: File solution.
source to share