[Melbourne-pm] overloading 'print'
Mathew Robertson
mathew.robertson at netratings.com.au
Fri Mar 17 00:07:03 PST 2006
>> Does anone know how to overload 'print'?
>>
>
> The short answer is that you can't. Print isn't one of Perl's overloadable
> functions. (The reason is that the syntax is special cased. You cannot make a
> user function with the same prototype.)
>
ok - I'm guessing this is because print can take a filehandle as the
first argument ?
> The longer answer is that you can... if you use IO::File and its print method.
> Then you can just subclass IO::File, and mask the print method to do what you need.
>
> The other non-overridable functions are listed in receipt 12.11 in the Perl
> Cookbook (1st Edition). Basically, if the keyword function in toke.c returns a
> negative number, then that function can't be overridden.
>
ok - thats a bit complicated. Any ideas on the implementation of the
sub-class of IO::File ?
ASIDE: The reason for wanting to override 'print' is... I have built a
language translation module (Locale::MakePhrase) which works quite well
- now I am working on simplifying its usage so that it can be used
within applications more easily. eg:
Currently if I want to print out a string translated (to say Chinese), I
would code something like:
use Locale::MakePhrase;
my $mp = Locale::MakePhrase->new(language => 'zn_ch', ....);
.....
print $mp->translate("Some text to translate");
thus to use the module within your application, would require the
application code to modified to support the L::M syntax. What I would
like to do is extend L::M to override 'print' so that the code becomes
much simpler:
use Locale::MakePhrase qw(print);
Locale::MakePhrase->new(language => 'zn_ch',...);
...
print "Some text to translate";
Thus with two simple lines at the top of the application, you
automagically get all of the translation facilities. If you choose to
use a different translation tool, you simply change those two lines -
thus saving you from having to re-code your app for the new API.
regards,
Mathew
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.pm.org/pipermail/melbourne-pm/attachments/20060317/a442d5f6/attachment-0001.html
More information about the Melbourne-pm
mailing list