How to Debug Perl Programs
No computer program ever works as intended on the first try. Programmers make mistakes, which can range from typos, to mistakes made because the programmer didn't understand something, to documentation mistakes, to bugs in Perl itself. When a program goes wrong, there are a number of techniques to debug it.
Instructions
-
Debug Perl Programs Manually
-
1
Use print statements. This is the most primitive way to debug Perl programs. If you know where the program is going wrong, put some print statements in to print out values. Remember to take these print statements out after you're finished, or at least comment them out.
-
2
Walk through the program in your head and compare what the values should be to what they actually are when the program runs.
-
-
3
Enable warnings, from the command-line with the -w switch, on the shebang line (that's the #!/usr/bin/perl line at the top) with the -w switch or with the "Use Warnings;" directive. The "Use Warnings;" directive will work on all platforms, while some platforms ignore the shebang line, making it so warnings might exist that you wouldn't know about.
-
4
Insist on no warnings, instead treating warnings like errors. Even though you might know why a warning occurs and that it's not a big deal right now, a future version of Perl might deprecate or change that behavior--in which case that warning just broke your program. Perl programs that run with no warnings will have fewer bugs.
Use the Perl Debugger
-
5
Start the Perl debugger. Start perl manually with the perl command and use the -d switch, followed by your script and any arguments you wish to pass to your script:
"perl -d myscript.pl arg1 arg2" -
6
List the program, as it's easier to view the code in the debugger when you are debugging it and need the line numbers to set breakpoints. You can list some or all of the program with the l command. You can specify a line number, a range of line numbers or a function name to list.
-
7
Set breakpoints using the "b" command in sections of the code you think are broken. Breakpoints tell the debugger to stop debugging when it reaches that line or function. They can be set on lines or functions and can have conditions attached. For example, to set a breakpoint on line 531 with the condition of "$a > 10", you would use the following command:
"b 531 $a > 10" -
8
Run the program, using the "r" command. This will run the program until a breakpoint is reached.
-
9
Step through the program. Once a breakpoint has stopped the program, step through the program line by line with the "n" command. Use this to isolate where the program is broken.
-
1
Tips & Warnings
Perl can warn you of common mistakes if you use the warnings flag.
The Perl debugger is often faster when you're having a major problem with your program, even if you have to look up commands to get the job done.