[comp.lang.perl] Local file handles?

elw@netex.netx.com (Edwin Wiles) (11/08/90)

I'm coding around the problem, but I'd like to know for future reference.

Is there any way to declare a file handle to be local to a given subroutine?

I didn't actually try this, and I don't think it would work, but it should
get the idea across:

sub Arecursive {
    local($somefile, @somejunk) = @_;
    open( local(INPUT), "< somefile" );		# This is the sticky line.
    while( <INPUT> )
    {
	...
	    @Bvalue = Arecursive( $_, @morejunk );	# This is why I want
	...						# "local(INPUT)".
    }
    close( INPUT );
    return @Avalue;
}

As you will notice, the routine doesn't really do anything.  It just
embodies the idea that I wanted to show:  Having "INPUT" be a filehandle
which is local to an instance of a recursive subroutine.

I've decided to code it so that all the IO occurs *before* the recursive
call, but it might have been nice to not have to do that...
-- 
Prefered.: elw@netx.com				Edwin Wiles
Alternate: ...!grebyn!netex!elw			NetExpress Inc., Suite 300,
Who?  Me?!?  Responsible!?!  Surely You Jest!	Vienna, VA, USA 22182

tchrist@convex.COM (Tom Christiansen) (11/08/90)

In article <9317@netxcom.DHL.COM> elw@netex.netx.com (Edwin Wiles) writes:
>Is there any way to declare a file handle to be local to a given subroutine?

    sub routine {
	local(*FILE);
	open (FILE, "foo");
	...
	do routine();
	...
	close FILE;
    }


works for me.  I don't believe this is (well-)documented.

--tom

lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) (11/09/90)

In article <9317@netxcom.DHL.COM> elw@netex.netx.com (Edwin Wiles) writes:
: Is there any way to declare a file handle to be local to a given subroutine?

There are two ways.

First, using an indirect filehandle:

$nextfh = 'fh000';

sub Arecursive {
    local($somefile, @somejunk) = @_;
    local($INPUT) = $nextfh++;		# magical increment
    open($INPUT, "< somefile" );
    while( <$INPUT> )
    {
	...
     @Bvalue = Arecursive( $_, @morejunk );
	...
    }
    close( $INPUT );
    return @Avalue;
}

or, using a * type glob:

sub Arecursive {
    local($somefile, @somejunk) = @_;
    local(*INPUT);
    open(INPUT, "< somefile" );
    while( <INPUT> )
    {
	...
     @Bvalue = Arecursive( $_, @morejunk );
	...
    }
    close( INPUT );
    return @Avalue;
}

Larry