Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: overloading the print function (or alternatives)

by chipmunk (Parson)
on Dec 04, 2000 at 10:42 UTC ( [id://44750]=note: print w/replies, xml ) Need Help??


in reply to overloading the print function (or alternatives)

Personally, I am leery of working around the problem as you are asking. So, here are my ideas, in order of preference, most preferred first.

1. I don't know much about the Everything Engine, but I wonder if it is possible to simply output the content-type header at the beginning of the program, before the programmer's code is called.

2. I would want to educate the users not to make this mistake. Of course, that can be difficult, because every new user may need to be educated about this issue. That can end up being more work than just fixing the problem. :)

3. Overload the print function. I'm not sure offhand whether print is in the list of built-in functions that can be overloaded. Someone else can address this one. :)

4. Tie the output filehandle. Tying a filehandle other than STDOUT and selecting it would be fine, except what if a programmer prints explicitly to STDOUT? (e.g. print STDOUT "hello $USER->{title}")
So, this example that I wrote ties STDOUT. Of course, when tying STDOUT, you have to untie STDOUT before printing to it for real. It may not be the cleanest approach, but it does work.

#!/usr/local/bin/perl -w use strict; package DelayPrint; sub TIEHANDLE { my $var = ''; bless \$var, shift; } sub PRINT { my $ref = shift; $$ref .= join( (defined $, ? $, : ''), @_) . (defined $\ ? $\ : '' +); } sub PRINTF { my $ref = shift; my $fmt = shift; $$ref .= sprintf($fmt, @_); } # flush: an additional function that returns the contents of the buffe +r # called via the object returned by tie() sub flush { my $ref = shift; my $text = $$ref; $$ref = ''; return $text; } package main; my $fh = tie *STDOUT, 'DelayPrint'; # tie STDOUT print "Hello world\n"; # print through the tied fileh +andle my $text = $fh->flush(); # get the text that was printe +d undef $fh; # erase the reference, untie *STDOUT; # untie the filehandle print $text; # print the text for real
Refer to perltie for more on tied filehandles and tying in general.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://44750]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (2)
As of 2025-07-18 01:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.