There's more than one way to do things | |
PerlMonks |
typeglobs and filehandlesby zzspectrez (Hermit) |
on Dec 20, 2000 at 22:45 UTC ( [id://47629]=perlquestion: print w/replies, xml ) | Need Help?? |
zzspectrez has asked for the wisdom of the Perl Monks concerning the following question: I am looking for a little enlightenment about typeglobs. I am writing module that stores a filehandle in an object. The filehandle is actually a filehandle to a socket but lets pretend it is just a file. This can be done doings something like the following.
This has worked fine. However, now I need to store multiple filehandles in the object and I want one subroutine to handle opening the files and returning the filehandle. Since a typeglob holds an entire symbol table entry, I know that trying to open all the files with FH and returning a typeglob will not work. So I do what I allways do when Im not sure what will hapen, I make a test applications. This is what I get.
This works fine, making a duplicate of the file, and returning data like the following:
Making slight modifications. Changing _open_read() and _open_write() so that the return is return *FH. I run this and the program has the same desired results.. The output of the filehandle keys changes to:
In my mind, I did not think this would work. Since FH goes out of scope at the end of the block, you would think you would need a reference to the typeglob to maintain access to it. Secondly, in the second example the object appears to have two references to the same filehandle *FOO::FH. However although they are opened as the same filehandle, the code operates on two seperate filehandles. How is this working? Lastly, I remember reading an article by Mark-Jason Dominus in Perl Journal on the uses of local. At the time I did not understand much about typeglobs or the diferences between local and my so I only glanced at the article. Looking back at the article I find an interesting tidbit that relates The article sugests using the following construct to get a glob that is disconected from the symbol table: $fh = do { local *FH };. Then you use $fh as if it was a filehandle. So I modify my test program like the following:
This works great! However, once again Im a little confused about how this trick works. First step I open my camel book and refresh reading about do. Ok, I feel stupid, I didnt know that a do block return the value of the last expression evaluated. This brings a little enlightenment. However, once again Im confused on how the block can return the value of *FH which loses scope once the block exits. I guess part of the confusion is, what exactly is being returned?!? According to the print of my hash, both variables point to the same glob *FOO::FH which was local in scope. Thanks!
Back to
Seekers of Perl Wisdom
|
|