in reply to Sending filehandles?

The "normal" way of achieving this is to use a lexical filehandle:
open(my $FILEHANDLE, ">", $filename) or die "Could not open file: $!"; print $FILEHANDLE "This goes to \$filename, as normal"; mysub( $FILEHANDLE );

I've used the 3-argument form of open, and included $! in die. That'll let perl tell you what the problem is rather than just "Could not open file".

$FILEHANDLE can be passed to a subroutine, just like any other variable.

Replies are listed 'Best First'.
Re^2: Sending filehandles?
by djp (Hermit) on Feb 11, 2008 at 02:28 UTC

    I've ... included $! in die.

    You've only done half the job there :-). If you don't put both the filename and the OS error in the error message, the user can't diagnose the actual problem. OP's (unhelpful) error message:

    Could not open file
    Your (fractionally more helpful) error message:
    Could not open file: Permission denied
    This:
    open(my $FILEHANDLE, ">", $filename) or die "Cannot open $filename: $!";
    yields a helpful error message:
    Cannot open /dev/secret: Permission denied
    To be super-picky, it's "Cannot open", not "Can't open", or "Could not open", or any other variation. In English, at least.

      Ahhh, a useless spelling and/or grammar criticism. Which is, of course, wrong, as such things always are. "Can't open" is just fine. "Can not" needs a space in the middle.

      But a good point about spitting out the filename in the error message.

        Well it wasn't intended to be a 'spelling or grammar' criticism, is was meant to be a 'standard error message' criticism.

        Why do you say 'cannot' cannot be used?