[Melbourne-pm] overloading 'print'

Mathew Robertson mathew.robertson at netratings.com.au
Tue Mar 21 19:01:49 PST 2006


:-)  which is the exact opposite of what I was trying to achieve....!

There is no question of using the object->print syntax as the preferred 
method to print, but usually thats not how people code when they want to 
print to STDOUT.

Mathew

Joshua Goodall wrote:
> 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
>
>
>   
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.pm.org/pipermail/melbourne-pm/attachments/20060322/988a9851/attachment-0001.html


More information about the Melbourne-pm mailing list