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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Preprocessing print statements
by Corion (Patriarch) on Nov 11, 2020 at 10:41 UTC | |
by mauroid (Initiate) on Nov 11, 2020 at 10:56 UTC | |
|
Re: Preprocessing print statements
by LanX (Saint) on Nov 11, 2020 at 12:19 UTC | |
by mauroid (Initiate) on Nov 11, 2020 at 13:42 UTC | |
by LanX (Saint) on Nov 11, 2020 at 13:55 UTC | |
by karlgoethebier (Abbot) on Nov 12, 2020 at 07:12 UTC | |
by LanX (Saint) on Nov 12, 2020 at 15:06 UTC | |
| |
|
Re: Preprocessing print statements
by salva (Canon) on Nov 12, 2020 at 09:27 UTC |