SPUG: Looking for a graceful way to deal with file handles and modules

Ken McGlothlen mcglk at serv.net
Tue Sep 28 18:06:36 CDT 1999

caseyt at metaip.checkpoint.com writes:

| Is there some graceful way that I can reference an open filehandle in my main
| script from the Perl module that has been called? Something pretty like
| main::filehandle?

It's possible, but awkward.  Your best bet is to refer to "man perlref" and
"man perldata", which explains all about these sorts of references.  From the
perlref page:

	[You can get a reference to a variable by] using the backslash operator
	on a variable, subroutine, or value.  [...]  Here are some examples:

		$scalarref = \$foo;
		$arrayref  = \@ARGV;
		$hashref   = \%ENV;
		$coderef   = \&handler;
		$globref   = \*foo;

	It isn't possible to create a true reference to an IO handle [...]
	using the backslash operator.  The most you can get is a reference to a
	typeglob [...].  [...]

Later on . . .

	A reference can [also] be created by using [...] the *foo{THING}
	syntax.  [This] returns a reference to the THING slot in *foo (which is
	the symbol table entry which holds everything known as foo).

		$scalarref = *foo{SCALAR};
		$arrayref  = *ARGV{ARRAY};
		$hashref   = *ENV{HASH};
		$coderef   = *handler{CODE};
		$ioref	   = *STDIN{IO};
		$globref   = *foo{GLOB};

	All of these are self-explanatory except for *foo{IO}.  It returns the
	IO handle, used for file handles (the open entry in the perlfunc
	manpage), sockets (the socket entry in the perlfunc manpage and the
	socketpair entry in the perlfunc manpage), and directory handles (the
	opendir entry in the perlfunc manpage).  [...]

	*foo{THING} returns undef if that particular THING hasn't been used
	yet, except [...] *foo{SCALAR} returns a reference to an anonymous
	scalar if $foo hasn't been used yet.  This might change in a future
	release.  [...]

So you could do something like this:

	sub get_record {
		my( $fh ) = shift;
		my( $s ) = <$fh>;
		return( $s );

and then

	$record = &get_record( *HANDLE );
	$record = &get_record( *HANDLE{IO} );

to get what you want.


 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    POST TO: spug-list at pm.org        PROBLEMS: owner-spug-list at pm.org
 Seattle Perl Users Group (SPUG) Home Page: http://www.halcyon.com/spug/
 SUBSCRIBE/UNSUBSCRIBE: Replace ACTION below by subscribe or unsubscribe
        Email to majordomo at pm.org: ACTION spug-list your_address

More information about the spug-list mailing list