[Melbourne-pm] overloading 'print'
Joshua Goodall
joshua at roughtrade.net
Tue Mar 21 17:23:23 PST 2006
On Wed, Mar 22, 2006 at 11:26:07AM +1100, Mathew Robertson wrote:
> Using IO::Wrap doesn't give that as I would have to change the syntax to:
>
> use IO::Wrap;
> no warnings;
> sub IO::Wrap::print {
> my $self = shift;
> print { $$self } "IO::Wrapped: ", @_;
> }
> use warnings;
> wraphandle(\*STDOUT);
> print "Blah";
>
> or something similar. However, this doesn't override 'print' as it
> produces the output:
man ... why take a nice OO package and shove a pitchfork in its guts? :)
anyway on closer examination IO::Wrap turns out to be the retarded child
of what it might be.
I had something in mind like:
package MyWrap;
use IO::Handle;
sub new {
my $class = ref($_[0]) || $_[0];
bless {io => $_[1], class => $class}, $class;
}
sub AUTOLOAD {
my $self = shift;
return if $AUTOLOAD =~ /::DESTROY$/;
$AUTOLOAD =~ s/^$self->{class}:://;
$self->{io}->$AUTOLOAD(@_);
}
sub print {
my $self = shift;
$self->{io}->print($self->{class}, ": ", @_);
}
package main;
$stdout = new MyWrap(\*STDOUT);
$stdout->print("Blah\n");
which is nice for libraries and anything where you shouldn't be relying
on global runtime state (i.e. any code in excess of 4 lines, excepting
perhaps debug code and other meta stuff)
I've used this approach for self-indenting filehandles (which then nests
very nicely). Although it was also finessed with gensym so that they
behaved a little more like IO::Handle objects.
/k
--
Josh "Koshua" Goodall "as modern as tomorrow afternoon"
joshua at roughtrade.net - FW109
More information about the Melbourne-pm
mailing list