Question

So basically what I mean is: is there a way for me to disable the function print's output when invoking a perl script at the command line? If not available in the base implementation of perl then maybe CPAN?

Things that I am aware of:

  • perl has a debugger
  • redirecting stdout to some file and then wiping it (useless in my case since I need STDOUT for something else)
  • having all lines that start with a print commented (doesn't scale, is ugly etc...)
  • redirecting in UNIX to dev/null

I am not referring to any warnings, exceptions, errors etc... Just the standard print function or any of it's very close siblings.

Similar to how you'd use C's #ifdef but at file scope and not having to write so much for so little.

I'm willing to install a cpan module in case it offers this kind of functionality.

I am limited to Perl 5.14.

Was it helpful?

Solution

Assuming you are writing this script yourself, or can edit it, something like below will work.

use Getopt::Long;
our $VERBOSE = 0;
GetOptions ('verbose+' => \$VERBOSE);
# ...
xprint(1, "Yadda yadda yadda");
# ...
sub xprint {
    my ($pri, $msg) = @_;
    print("$msg\n") if $pri >= $VERBOSE;
}

EDIT:

Or without priority levels:

use Getopt::Long;
our $VERBOSE = '';
GetOptions ('verbose' => \$VERBOSE);
# ...
xprint("Yadda yadda yadda");
# ...
sub xprint {
    # can also be replaced with printf(@_) for more cowbell.
    print("$_[0]\n") if $VERBOSE;
}

EDIT:

As an aside, for #ifdef functionality, replace the whole getopt section with a simple constant:

use constant VERBOSE => 1;

And remove the $ from VERBOSE after the print statement:

print("$_[0]\n") if VERBOSE;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top