How can I make a filehandle local to a subroutine? How do I pass filehandles between subroutines? How do I make an array of filehandles?

As of perl5.6, open() autovivifies file and directory handles as references if you pass it an uninitialized scalar variable. You can then pass these references just like any other scalar, and use them in the place of named handles.

	open my    $fh, $file_name;
	open local $fh, $file_name;
	print $fh "Hello World!\n";
	process_file( $fh );
Before perl5.6, you had to deal with various typeglob idioms which you may see in older code.

	open FILE, "> $filename";
	process_typeglob(   *FILE );
	process_reference( \*FILE );
	sub process_typeglob  { local *FH = shift; print FH  "Typeglob!" }
	sub process_reference { local $fh = shift; print $fh "Reference!" }
If you want to create many anonymous handles, you should check out the Symbol or IO::Handle modules.
Back to perlfaq5