[Melbourne-pm] overloading 'print'

Jacinta Richardson jarich at perltraining.com.au
Fri Mar 17 03:03:05 PST 2006


Mathew Robertson wrote:

>>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 ?

That's the one!

> ok - thats a bit complicated.  Any ideas on the implementation of the
> sub-class of IO::File ?

Nope.  Upon further consideration it might not help anyway for what you're
trying to do, as I think you'd have to do $fh->print....

> 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.

Personally I think that's a little bit evil.  What if I actually want to print?
 Surely it's not that hard to write an editor substitution for replacing "print"
with "print $mp->translate" where desired.  But sure, as an academic exercise,
how could you do this?  Perhaps the following might help.

use Filter::Handle qw/subs/;

Filter \*STDOUT, sub {
            print $mp->translate $_;

};

All the best,

    Jacinta


-- 
   ("`-''-/").___..--''"`-._          |  Jacinta Richardson         |
    `6_ 6  )   `-.  (     ).`-.__.`)  |  Perl Training Australia    |
    (_Y_.)'  ._   )  `._ `. ``-..-'   |      +61 3 9354 6001        |
  _..`--'_..-_/  /--'_.' ,'           | contact at perltraining.com.au |
 (il),-''  (li),'  ((!.-'             |   www.perltraining.com.au   |




More information about the Melbourne-pm mailing list