Xiong has asked for the wisdom of the Perl Monks concerning the following question:
I want to accept a filehandle given in the use line of my module:
use My::Module $fh;This seems straightforward enough:
package My::Module; our $fh; sub import { shift; # throw away my own package name $fh = shift; if ( not -w $fh ) # check to see it's a good filehandle { die 'Bad filehandle in use My::Module' }; } sub later { print $fh 'Arbitrary text.'; } 1;
Should I allow for the possibility that caller may decide to supply the filehandle using another syntax? If so, what should I allow?
use My::Module STDOUT;
The code I've actually written works fine for:
use My::Module *STDOUT;It works okay, too, for:
use My::Module $fh;... but with that, there's a fundamental complication which I did not consider while hurrying off in the other direction: The use line executes as a BEGIN block so, even though caller may appear to open $fh before, he doesn't, unless he does so in a previous BEGIN block:
BEGIN { open $::fh, '>>', '/var/foo.log'; } use My::Module $::fh;
... and of course there are other approaches caller might employ. None of this, strictly speaking, is my worry (as author of My::Module); I just have to deal with the passed-in argument.
This is probably lunacy:
use My::Module STDOUT;... or at least I can hope that nobody will be go down that road.
Is it worthwhile to support:
use My::Module 'STDOUT';or perhaps:
use My::Module '/var/foo.log';... or is that just too much gingerbread? Do you have a preferred syntax you'd like to see implemented?
rm ',' per bart.
Marginally more legitimate example code per almut.
2010-05-31Agree with tye that it's ugly to accept:
use My::Module "STDOUT";... I never even considered it. I don't really want to accept either of:
use My::Module STDOUT;I think I'll continue to support, because so commonly used:
use My::Module *STDOUT;...but I'll add support for:
use My::Module \*STDOUT;I see that almut has a good word for:
use My::Module '/var/foo.log';This may be just a bent feeler gauge off from the paygrade of the basic module under consideration but the small project as a whole contemplates opening filenames passed in as literal strings.
ikegami speaks wisely that opening $fh in a BEGIN block before the use line is icky. There isn't really an alternative, this being a source filter -- not without way too much hackery on existing code. Again, a helper/wrapper module is intended for open and pass in one line. I'm going to escalate the priority of this.
|
|---|