thor has asked for the wisdom of the Perl Monks concerning the following question:

Greetings all,
I'm trying to create a module to read an proprietary file format, and have everything working, however, I'd like to put a little sugar on it.

Instead of calling tie *FH, "thor", "myfile", I'd like to be able to mask the tie with a subroutine in the same package. Here's what I have in the package:

package thor; use strict; use Carp; require Exporter; our($VERSION, @ISA, @EXPORT); $VERSION = "0.1"; @ISA = qw(Exporter); @EXPORT = qw(rdw_open); sub rdw_open(*$;@) #need a file handle and a name, but allow more for +the 3 arg open... { local *fh = shift; tie \*fh, __PACKAGE__, @_ ; } sub TIEHANDLE { my $class = shift; my $filename = shift; open my $self, $filename or croak "Couldn't open $filename: $!"; bless $self, $class; return $self; }
So, then in my script, I'd like to be able to do this:
#!/usr/bin/perl use thor; rdw_open(FH,"myfile") or die "Couldn't open myfile: $!"; # replaces tie *FH, "thor","myfile"

Is this possible?
Incidentally, I tried moving the rdw_open sub into my script and it works, which I find a bit strange...

Replies are listed 'Best First'.
Re: Can you tie a filehandle in your own package?
by Felonious (Chaplain) on Mar 01, 2002 at 05:57 UTC
    sub rdw_open(*$;@) # need a file handle and a name, but allow more fo +r the 3 arg open... { my $fh = shift; tie *{$fh}, __PACKAGE__, @_ ; }
    rdw_open(*FH, "myfile") or die "Couldn't open myfile: $!";
    -- O thievish Night, Why should'st thou, but for some felonious end, In thy dark lantern thus close up the stars? --Milton
      This is great! (++ for you) One last question, then I'll be quiet for a while: Is there a way to change the subroutine call to use a file handle rather than a typeglob? i.e.
      rdw_open(FH, "myfile") or die "Couldn't open myfile: $!";
      I'd like to make this look like regular open as much as possible, and the level of peoples perl around these parts is not so great as to remember why they need the * in front of their filehandle.

      Thanks,
      thor
        It starts getting ugly:
        sub rdw_open(*$;@) # need a file handle and a name, but allow more for + the 3 arg open... { my $fh = shift; if (not ref($fh) eq 'GLOB') { $fh = "*" . (caller())[0] . "::" . $fh; } { no strict; tie *{$fh}, __PACKAGE__, @_ ; } }
        -- O thievish Night, Why should'st thou, but for some felonious end, In thy dark lantern thus close up the stars? --Milton