Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Preprocessing print statements

by Corion (Patriarch)
on Nov 11, 2020 at 10:41 UTC ( [id://11123580]=note: print w/replies, xml ) Need Help??


in reply to Preprocessing print statements

Your idea of "auto-redirect"ing a filehandle to a subroutine is possible using a tie'd filehandle (see Tying FileHandles). This is not a sane solution for a long-term approach, but for the short term it will work:

package GreppedFileHandle; use strict; sub TIEHANDLE { local *FH; open my $self, \*FH; bless $self, shift } sub PRINT { my $self = shift; my $output = "@_"; if( $output =~ /\Q$::GREP_STR\E/ ) { print( STDOUT $output ); } else { print "Swallowed a line\n"; }; } package main; our $GREP_STR = '123'; # needs to be 'our', not 'my' tie *grep_fh, 'GreppedFileHandle'; print STDOUT "Header - always print this\n"; print grep_fh "My line with 123\n"; ## printed at the terminal print grep_fh "My line with 456\n"; ## not printed

For the long term approach, you should look at a logger framework (like Log::Log4perl) or a "simple" logging subroutine like your &myprint() to centralize the logging.

Replies are listed 'Best First'.
Re^2: Preprocessing print statements
by mauroid (Initiate) on Nov 11, 2020 at 10:56 UTC

    This works perfectly! Thank you so much!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (5)
As of 2024-04-19 06:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found