code_junkie

How can I hook into Perl's print?

Nov 13th, 2011
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. sub CheckPrintOutput
  2. {
  3. my @output = @_; # args passed to print eventually find their way here.
  4. foreach my $value (@output) {
  5. Log->log($value) if $value =~ /warning|error|notice|attention/i;
  6. }
  7. }
  8.  
  9. package IO::Override;
  10. use base qw<Tie::Handle>;
  11. use Symbol qw<geniosym>;
  12.  
  13. sub TIEHANDLE { return bless geniosym, __PACKAGE__ }
  14.  
  15. sub PRINT {
  16. shift;
  17. # You can do pretty much anything you want here.
  18. # And it's printing to what was STDOUT at the start.
  19. #
  20. print $OLD_STDOUT join( '', 'NOTICE: ', @_ );
  21. }
  22.  
  23. tie *PRINTOUT, 'IO::Override';
  24. our $OLD_STDOUT = select( *PRINTOUT );
  25.  
  26. sub PRINTF {
  27. shift;
  28. # You can do pretty much anything you want here.
  29. # And it's printing to what was STDOUT at the start.
  30. #
  31. my $format = shift;
  32. print $OLD_STDOUT join( '', 'NOTICE: ', sprintf( $format, @_ ));
  33. }
  34.  
  35. open my $fh, ">log.txt";
  36. print "test1n";
  37. my $current_fh = select $fh;
  38. print "test2n";
  39. select $current_fh;
  40. print "test3n";
  41.  
  42. package PsychicSTDOUT;
  43. use strict;
  44.  
  45. my $c = 0;
  46. my $malformed_header = 0;
  47. open(TRUE_STDOUT, '>', '/dev/stdout');
  48. tie *STDOUT, __PACKAGE__, (*STDOUT);
  49.  
  50. sub TIEHANDLE {
  51. my $class = shift;
  52. my $handles = [@_];
  53. bless $handles, $class;
  54. return $handles;
  55. }
  56.  
  57. sub PRINT {
  58. my $class = shift;
  59. if (!$c++ && @_[0] !~ /^content-type/) {
  60. my (undef, $file, $line) = caller;
  61. print STDERR "Missing content-type in $file at line $line!!n";
  62. $malformed_header = 1;
  63. }
  64. return 0 if ($malformed_header);
  65. return print TRUE_STDOUT @_;
  66. }
  67. 1;
  68.  
  69. use PsychicSTDOUT;
  70. print "content-type: text/htmlnn"; #try commenting out this line
  71. print "<html>n";
  72. print "</html>n";
Add Comment
Please, Sign In to add comment