views:

53

answers:

2

Is it possible to add the -w tag to the first line of a perl program, then run the program from a shell like bash or dos and write all of the warnings into a file?

perl somescript.pl > somefile.txt

This is a throwback to desk checking COBOL programs at school. I'd like to have all of the warnings in front of me on a piece of paper so I can go through my program and fix them one-by-one. If the above command doesn't work, is there a way programmatically to get all of a script's warnings into a file? Thanks guys!

+4  A: 

Try this:

perl somescript.pl 2&> somefile.txt

When you use plain redirection (>), you only redirect the standard program output stream, whereas the warnings get saved to standard error output stream. See for example the Bash Reference Manual.

There is also a Vi::QuickFix module on CPAN that can save the warnings into a file that you can load into Vim and inspect all the warnings without hunting the line numbers by hand. (Google for vim quickfix.) I did not try it myself, though.

zoul
+1  A: 

zoul handled the redirection stuff, so here's the amazingly complex answer on warnings.

Just call the program like so: perl -w script.pl

This forces warnings to be enabled everywhere in the script and all modules. It is really better to use the warnings pragma in every module you write. See perldoc perllexwarn for more info on this subject.

Another trick that is nice when debugging is to use Carp::Always. If forces a complete stack trace on every error. I find this very very helpful. Simply run your script like so:

perl -MCarp::Always somescript.pl

or to get it into a file:

perl -MCarp::Always somescript.pl 2&> somefile.txt

And finally, I'll digress from your question a bit more. Many people like to instrument their code by using a logging library like Log4Perl. Tools like this let you enable logging at a certain level (normal or debug for example) or over specific parts of your application on individual runs of your code. This is the final(?) evolution of the debugging print statement. It can be quite useful in debugging failures while in development, and in the field once you have reached the maintenance phase.

daotoad

related questions