in reply to overloading the print function (or alternatives)
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.
Refer to perltie for more on tied filehandles and tying in general.#!/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
|
|---|