Path: utzoo!attcan!uunet!fernwood!apple!usc!elroy.jpl.nasa.gov!jpl-devvax!lwall From: lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) Newsgroups: comp.lang.perl Subject: Re: Operations on filehandles Message-ID: <7020@jpl-devvax.JPL.NASA.GOV> Date: 8 Feb 90 06:35:28 GMT References: <1004@frankland-river.aaii.oz.au> Reply-To: lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) Organization: Jet Propulsion Laboratory, Pasadena, CA Lines: 57 In article <1004@frankland-river.aaii.oz.au> pem@frankland-river.aaii.oz.au (Paul E. Maisano) writes: : I was wondering what sort of object a filehandle was and what can be done : with one besides printing to them etc. : : Specifically, can you save them in a local context in some way, similar to : what the local() function does with variables. : : For example, if I open a file in a subroutine and use a file handle called : FILE which I open and then close, how do I know I'm not stomping on : another filehandle called FILE which has already been opened somewhere else : in my program. : : I could create a package to avoid the possibility of a naming conflict but : this does not really solve the problem. I believe you can do a local on a name using the type globbing syntax: sub foo { local(*FILE); open(FILE,'foo'); etc. I haven't exercised it heavily, but the code is supposedly there to create a new name if you aren't assigning another name to *FILE. Just as normal variables created with a null value when you don't assign something to them. : What if I want to write a recursive subroutine which opens a file ? How do : I keep separate filehandles for each recursive call ? Same way. : Is there a simple way to do this or must I generate a unique filehandle name : on each invocation ? That's pretty simple, though it's easy to generate unique filehandles too: $genhandle = 'AAAAAA'; # increments to AAAAAB sub foo { local($FILE) = $genhandle++; # magical autoincrement open($FILE,'foo'); ... &foo(); ... close $FILE; } But I THINK the other way is more efficient, if you reference the filehandle much, since it has to do a symbol table lookup every time you say $FILE, but references to FILE already point to the symbol table entry upon compilation. But it probably takes a little longer to local(*FILE) than local($FILE). It's 6 1/2 of one, and uh, uh, half a baker's dozen of the other. Larry