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

Hello Monks. I would like to overload the print statement so anything that is printed to the console will show up in a text box as I am using the win32::GUI. Output is the name of my txt box. below is what i tried but doesn't work. Any suggestions would be of great help.
sub print { shift; $main->OutPut->Append(@_); }

Replies are listed 'Best First'.
Re: print overloading
by ikegami (Patriarch) on Oct 29, 2009 at 19:16 UTC
    Can't.
    $ perl -le'print defined(prototype("CORE::print")) || 0' 0

    But honestly, that's not what you want anyway. What if the program also uses printf or syswrite? What if the program wants to write to a file?

    You want to present the interface of a variable, but with custom functionality. That's what magic is for. Specifically, you want to tie the handle you want redirected (presumably STDOUT). See Tie::Handle

      Thanks. So what would the code look like if i wanted to use the Tie::Handle?

        In its most simple case, you could do something like this:

        #!/usr/bin/perl package MyHandle; sub TIEHANDLE { my $class = shift; return bless { @_ }, $class; } sub PRINT { my $self = shift; print STDERR "tied PRINT: @_\n"; # put your implementation here... } package main; tie *STDOUT, "MyHandle"; print "foo", "bar"; # "tied PRINT: foo bar" on STDERR

        (But don't try to print "foo" (i.e. print to the tied STDOUT handle) within the PRINT() method itself — this might do nasty things like segfaulting...)

        See Tying FileHandles for how to do it in a more complete way.

        ___

        BTW, you could pass further arguments to the tie statement, e.g.

        tie *STDOUT, "MyHandle", bar => 'quux';

        These will be passed to the constructor (TIEHANDLE), which it turns into object attributes to utilize for whatever purpose you like. In the example, when dumping $self (using Data::Dumper), you'd then have

        $VAR1 = bless( { 'bar' => 'quux' }, 'MyHandle' );