Perl FAQ 4.6: How can I make a file handle local to a subroutine?

Perl FAQ 4.6

How can I make a file handle local to a subroutine?

You must use the type-globbing *VAR notation. Here is some code to cat an include file, calling itself recursively on nested local include files (i.e. those with #include "file", not #include ):

sub cat_include {
    local($name) = @_;
    local(*FILE);
    local($_);
    warn "\n";
    if (!open (FILE, $name)) {
	    warn "can't open $name: $!\n";
	    return;
    }
    while (<FILE>) {
	if (/^#\s*include "([^"]*)"/) {
	    &cat_include($1);
	} else {
	    print;
	}
    }
    close FILE;
}


Other resources at this site: