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

If your object is basically just a file handle (for example, if it's an instance of Symbol or it derives from IO::Handle), how do you store properties in it?
  • Comment on Adding properties to a blessed file handle reference

Replies are listed 'Best First'.
Re: Adding properties to a blessed file handle reference
by runrig (Abbot) on Mar 29, 2007 at 20:15 UTC
    See IO::String and IO::Scalar which do exactly that. A file handle is a glob, and has hash, array, and scalar (and some other) slots which you can access (see perldata I think..and look for "typeglob").

    Dominus has some slides that may help on that.

Re: Adding properties to a blessed file handle reference
by xdg (Monsignor) on Mar 29, 2007 at 20:37 UTC

    You can do this with inside-out objects. See the File::Marker example in my YAPC::NA 2006 talk.

    Class::InsideOut makes this even easier.

    package My::File::Class; use base 'IO::File'; use Class::InsideOut qw/public id register/; public some_property => my %some_property; sub new { my $class = shift; my $self = IO::File->new( @_ ); register( bless $self, $class ); return $self; } 1;

    Use like this:

    use My::File::Class; my $obj = My::File::Class->new( "filename.txt" ); $obj->some_property("foo");

    -xdg

    Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

Re: Adding properties to a blessed file handle reference
by friedo (Prior) on Mar 29, 2007 at 20:26 UTC

    Since filehandles are typeglobs, you can access its associated hash and stick stuff in it. For example,

    sub set_foo { my $self = shift; my $val = shift; ${ *$self }{foo} = $val; }

    Update: I think you can also just say *$self->{foo} = $val; which is less ugly.