http://qs1969.pair.com?node_id=11123579

mauroid has asked for the wisdom of the Perl Monks concerning the following question:

I have a long script that uses print (to STDOUT) in various places to print data to a terminal. Now I need to add a 'grep' option within the script so that only lines that match a certain regular expression are printed; all the rest are not printed.

I would be OK with adding a new FILEHANDLE in front of every print statement, but I would want to avoid calling my own print subroutine every time I want to do a print. So something like this would be OK (only the first line should be printed in STDOUT, the second would not be printed):

my $GREP_STR = "123"; ## a global var print GREP_FH "My line with 123\n"; ## anywhere in the code print GREP_FH "My line with 456\n";

but not this

&myprint("My line with 123\n"); &myprint("My line with 456\n");

Ideally I would also want the ability to print lines that override the 'grep' and are printed anyway, but that's optional. So something like this:

$GREP_STR = '123'; 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

I thought that by using 'select' I could auto-redirect the STDOUT to maybe a subroutine, and then decide there if I want to print something or not, but it seems like 'select' only redirects to an actual FILEHANDLE and can't redirect to a subroutine.