December 2005 Archives
Thu Dec 22 16:59:43 CET 2005
Perl Typeglobs, Filehandles and Hashes
I was trying to get a Perl object akin to IO::Handle, i.e. some instance I can use like a file handle in print $obj $data, but also like an object in $obj->mymethod(). Not knowing perl well enough, it took me two days of research and the help of several #perl regulars... But now I can present two solutions: one using tie and one using overloading:
#! /usr/bin/perl -w
package TestGlob;
use strict;
use Symbol qw(gensym);
sub new {
print STDERR "TestObj::new\n";
my $class = shift;
my $self = gensym();
tie *$self, $class, $self;
bless $self, $class;
$$self->{'data'} = 'Foo';
return $self;
}
sub print {
print STDERR "TestObj::print\n";
my $self = shift;
print $$self->{'data'}, "\n";
print @_;
}
sub TIEHANDLE {
print STDERR "TestGlob::TIEHANDLE\n";
my $class = shift;
my $self = shift;
return bless($self, $class);
}
sub PRINT {
print STDERR "TestObj::PRINT\n";
my $self = shift;
print $$self->{'data'}, "\n";
print @_;
}
1;
package TestObj;
use strict;
use overload '*{}' => 'to_glob';
sub new {
print STDERR "TestObj::new\n";
my $class = shift;
my $self = {};
$self->{'handle'} = \*STDOUT;
bless $self, $class;
return $self;
}
sub print {
print STDERR "TestObj::print\n";
my $self = shift;
print "Hallo\n";
}
sub to_glob {
print STDERR "TestObj::to_glob\n";
return shift->{'handle'};
}
1;
package main;
use strict;
my $t = new TestGlob();
$t->print("Fasel\n");
print $t "blah\n";
Sun Dec 4 19:10:30 CET 2005
End Of Story
Finally, www.onaras.ch is dead and likely to stay so. Some of us where expecting this for a while now, and personally, I'll be at OPIT Solutions AG starting 2.1.2006 (that's 1/2/2006 for you over there), so it wasn't exactly a big surprise, but the speed was memorable. On Wednesday, the big meeting where everybody who had not already quit got his nice letter telling him to leave by the end of the year, and finally on Friday it was time to hand over the keys and take your private stuff home. An after work beer with the cow-orkers, and that was it.