Softpanorama

May the source be with you, but remember the KISS principle ;-)
Home Switchboard Unix Administration Red Hat TCP/IP Networks Neoliberalism Toxic Managers
(slightly skeptical) Educational society promoting "Back to basics" movement against IT overcomplexity and  bastardization of classic Unix

Debugging Perl Scripts

News

Perl for Unix System Administrators

Recommended Books Recommended Links

Understanding perl diagnostic me

Perl Style

Cheat sheets

Perl Debugger Stepping Commands Viewing variables from Perl debugger Perl Debugger Breakpoint Commands Viewing the Perl code during script execution Perl Error Checklist Perl debugging Tips Perl Error Checklist
Perl POD documentation Perl Xref Regular expressions Debugging regular expressions Perl Programming Environment
Debugging Software Testing Program understanding Pretty Printing Perl Tips Humor Etc

Introduction

A more experienced programmer not necessary makes less bugs.
He just can find what went wrong more quickly.

Debugging of Perl scripts is a challenging problem due to the complexity and power of the language. The quality of the debugger is very good, and it does have GUI based version.

I personally prefer command line version as it allows more flexibility.

Two basic commands to start experimentation are h and q. command h provides help so you can see what commands are available and experiment with them. command q allow you to leave the debugger.  Another very useful command is R for restart. There are multiple useful YouTube tutorials. You can start with Gabor Szabo series of YoutTube tutorials.  Gabor Szabo is the author of Padre (impressive Perl IDE, although it became abandonware for the lack of support) and a well-known expert in Perl:

The most common error -- misspelled variables can be detected during compilation if you use option -w. Putting pragma use warnings in your script can do the same. Also recommended is use strict.

The debugger's command-line history mechanism provides command-line editing like many shells, but you need correct build of Perl interpreter to enjoy this  feature. It might be available but  it might be not.

Note: you can always execute previous lines with using exclamation point syntax (!).

Highlights of Perl debugger

Perl debugger is similar to many other line-oriented debuggers. That means that it has powerful and pretty complex instruction set. Complexity of the debugger is such that few people learn it deeper that some very superficial level. I am one of such people :-). Most professionals that I know work with debugger consulting personal customized cheat-sheet. Creation of such reference card, for example using perl-debugger-refcard-a4 by Andrew Ford, or this page as a template is a must. For more inspiration see cheat-sheets section of Recommended Links

Complexity of the debugger is such that few people learn it deeper that some very superficial level. I am one of such people :-). Most professionals that I know work with debugger consulting personal customized cheat-sheet. Creation of such reference card, for example using perl-debugger-refcard-a4 , or this page as a template is a must. For more inspiration see cheat-sheets section of Recommended Links

Among unique capabilities of Perl debugger that any programmer should know and know well:

Starting and exiting the debugger

Like with, say, vi or other command line programs with complex instruction sets, the level zero of debugger mastery is to know how to get into debugger, how to get help and how to exit the debugger. Here are answers of those three fundamental questions:

Minimal set of command to use with Perl debugger

The problem with command line debuggers is that you need to remember set of commands to use it productively. It is not an easy task especially if you do not use debugger daily. One obligatory thing to do is to print a cheat-sheet and put it above your monitor. I for example noticed that from one debugging session to another I forget even some essential commands.

If you think that because I wrote this page I use all the commends discussed you are deeply mistaken. I use a very primitive subset close to the minimal set described below. And what is interesting any my attempts to use a richer subset fail -- from one episode during which I can benefit from this additional functionality to another I completely forget how to use it.

A typical person probably is not able to remember more then seven Perl debugger commands. In this sense I am a typical person although it is more correctly to say not seven commands but seven groups of similar command as brain works in hierarchical chunks. I typically use just the following seven commands:

  1. n -- single step without stepping into subroutines. You need to enter it only the first time. After that pressing Enter will repeat the command.
  2. s -- single step with stepping into subroutines. This is an alternative command to n and it is useful if you need to look how a particular subroutine behaves on the text data.
  3. c -- continue processing until a break of some sort. In the simplest (and most useful) case a line number can serve as one time (temporary) breakpoint, for example:
    c 200

    NOTE: you can create subroutine stop, and  insert it using the editor at points where you need to switch  to interactive mode.

    sub stop
    {
       $DB::single = 1;
    }
    
  4. l min+incr -- displays "window" of the program's code of incr lines. Without parameters defaults to 10 lines window from the last executed line. Repeat of command without parameters bring the next ten lines and so on. With two parameters shown lists incr+1 lines of the script starting at min.
  5. p -- a regular Perl print command, so you can use the normal Perl syntax there, for example:
    p "$ARGV[0]\n$_";
  6. ! number -- Redo a previous command (without number defaults to the previous command). Perl debugger numbers debugger commands in its prompt so scrolling back you can see what command that you entered needs to be repeated.
  7. H -- lists the debugger commands history. First of all it can serve as an alternative to scrolling back. This way you will see commands that you already entered in this session. You can limit output by providing a number prefixed with a minus sign. For example:
    H -5
    it will displays the last 5 commands. Only commands longer than one character are stored in the history. (s or n, are omitted from history).

Intermediate set of commands

Intermediate set of commands that I feel can improve my productivity if (and only if) I am able to learn it (which is not a problem) and don't forget from one debugging session to another (which is a real problem).

In my view this intermediate set consists of less then 21 (the next after 7 magic number the signified the next level of complexity of remembering a set of items ;-). People don't usually remember sets larger then 7 as one chunk. They split them into subgroups. Commands below are split into five groups with at most seven commands in the largest group:

  1. Stepping commands
  2. Breakpoint commands
  3. Viewing the program code and debugger commands during execution
  4. Viewing variables during execution
  5. History mechanism for debugger commands, sourcing of external commands sets.
  6. Switching to step-by-step execution dynamically from within the program

    This is actually not a debugger command but executable Perl statement. You can switch to step-by-step execution using Perl debugger from within your Perl program itself. to transfer control back to the debugger use the following statement, which is harmless if the debugger is not running:

    $DB::single = 1;
    If you set $DB::single to 2, it's equivalent to the n command, whereas a value of 1 emulates the s command.

    The $DB::trace variable should be set to 1 to simulate the t command.

csh-like history mechanism

Debugger resembles shell in a sense that it it maintain the history of commands that you can print and has mechanism for retrieving previous commands. History mechanism is based on two commands:

Aliases

You can define an alias for any command. Alias command starts with "=" and has two arguments the alias for the command and command itself (should be put "as is" without surrounding it with double quotes. This is useful for printing commands, for example

= pa for (@a) { print "$_:"}

Also you also define small subroutines as aliases

Sourcing debugging commands from the file

Debugger also allows you to source commands from the file.

that means that you can define your aliases in a file and source them at the beginning of the session like you do with shell.

Anything reusable during the debugging of the particular program can be refined and put into special file. For example for script fileinfo.pl the file will be fileinfo.dbrc. Typically aliases and watch expression are reusable and you can benefit from saving them in the file so that you can reuse them in later debugging sessions.

Some additional commands

Watching variables

You can set a watch-expression (an expression which triggers a halt if its value changes) with the "w" command, as in the following example:

DB<1> w $count 
DB<<3>> L 
Watch-expressions: 
$count

Now that the watch-expression has been set, you can see how it works by writing some code to alter the value of the $count variable.

The debugger will display a message every time the variable's value changes.

Actions

Actions are similar to breakpoints and watches. You can supply line number to which action is applied and the command to be performed as an action, for example

a 53 print

But the most useful usage of actions is to verify the assertions into your script as well as ensure that a particular expression is to be evaluated whenever a specified line is executed or a specified subroutine is entered.

The simplest, but educational case of using the action and to print the value of a variable with each iteration of the loop:

main::(test.pl:8):      looper();
  DB<1> v
5==>    # This program demonstrates the Perl debugger.
6:      looper();
7:      sub looper {
8:         my $arg = 0;
9:         while ($arg < 10) {
10:             ++$arg;
11:          }
12:     }
  DB<1> a 10 print "arg is now $arg... "
  DB<2> b 10 ($arg > 8)
  DB<3> c
arg is now 0... arg is now 0... arg is now 1... arg is now 1... arg is now 2...
arg is now 2... arg is now 3... arg is now 3... arg is now 4... arg is now 4...
arg is now 5... arg is now 5... arg is now 6... arg is now 6... arg is now 7...
arg is now 7... arg is now 8... arg is now 8... 
main::looper(testDebugger.pl:1)
:           while ($arg < 10) {
  DB<3> ow 9...

You can see on the last line that the output generated by actions can become intermixed with that generated by the debugger itself.

If no command is specified, the action on the specified LINE is deleted. With neither LINE nor COMMAND, the action on the current line is deleted.

A command deletes all actions.

Overview of literature

Documentation available includes

There are couple of chapters available from free Perl books


Top Visited
Switchboard
Latest
Past week
Past month

NEWS CONTENTS

Old News ;-)

[Oct 15, 2020] Perl debugger and my variables by you !!!

Oct 12, 2020 | perlmonks.org

likbez

my $a=$x=$y=$z = foo()
Here my attribute does not propogate like in case of comma. It applies only to $a, right ? But now the fun starts But now the fun starts
DB<3> use v5.10

DB<4> my $a=$x=$y=$z = 1

DB<5> say "|$a|$x|$y|$z|"
||1|1|1|  
DB<6> unless( defined($a) ){ say "a is undefined"}
a is undefined
why $a remains uninitialized?

LanX on Oct 12, 2020 at 07:22 UTC

Re^3: What's happening in this expression? > why $a remains uninitialized? It's not the same It's not the same $a The lexical scope in the debugger is limited to the The lexical scope in the debugger is limited to the The lexical scope in the debugger is limited to the eval'ed line. Skip the my to avoid this effect.
edit

Fletch already explained it in detail

Re^3: What's happening in this expression? (Updated)

Re^3- What's happening in this expression- (Updated)

Fletch on Oct 12, 2020 at 03:25 UTC ( # 11122722 = note : print w/replies , xml ) Need Help??

in reply to Re^2: What's happening in this expression? (Updated)
in thread What's happening in this expression?

The debugger is a bad place to play with scoping like this. In effect when you evaluate single lines like this they're more like doing an eval within the scope of the program (more or less; I'm sure someone more familiar with the perl5db could give more specifics).

It's kind of like (handwaving) textually shimming in say DebugDump( eval { YOURTEXTHERE } ) into wherever you're looking at and seeing the result.

This means that your my declaration is happening inside of a transient scope (that single eval statement) and then it's going away. Since the my was affecting only $a when you check for defined-ness it fails because the package $a wasn't defined (however your modifications to $x et al changes the package versions of those and the values do persist after the statement).

$ cat test.pl use 5.032; my $foo = 10; say qq{foo: $foo} $ perl -d test.pl Loading DB routines from perl5db.pl version 1.57 Editor support available. Enter h or 'h h' for help, or 'man perldebug' for more help. main::(test.pl:2): my $foo = 10; DB<1> x $foo 0 undef DB<2> n main::(test.pl:3): say qq{foo: $foo} DB<2> x $foo 0 10 DB<3> my $foo = 20 DB<4> x $foo 0 10 DB<5> my $foo = 20; say qq{foo: $foo} foo: 20 DB<6> x $foo 0 10 [download]

Simple rule of thumb I tend to follow is just don't use my (or state or our ) from the debugger command line to try and affect anything outside of that immediate command line.

The cake is a lie.
The cake is a lie.
The cake is a lie.

likbez on Oct 15, 2020 at 04:08 UTC

Re^4: What's happening in this expression? (Updated)

You are right. My variables are not always treated correctly, although recently the situation improved. I remember that in the past you just can't work with my variables at all. I just have a utility that stripped my moving them to tail comments and then reversed the situation. But now the usage of my "official" as it is forced by the strict pragma. Which means that such a situation is less acceptable.

Also if you are using recursion my attribute can't be stripped at all. So this is a clear deficiently.

That's sad, because IMHO the debugger is the crown jewel of Perl language environment and remains in certain areas unmatched by competition(macros, flexibility of c command, etc.) Possibility of b lineno ($var eq "value") is indispensable for debugging complex programs. That's what I always stress in my Perl advocacy efforts" "Unmatched by competition."

So any deficiencies here are "highly undesirable."

That's, of course, raises the question of development priorities...

[Oct 15, 2020] Perl - Breakpoints of a Debugger

Oct 15, 2020 | www.geeksforgeeks.org
DB<15> b valuedir

This creates a breakpoint at the very first executable statement of the subroutine valuedir.

b-command can also be used to halt a program only when a specified condition meets.
For example, below mentioned command tells the debugger to halt when it is about to execute line 12 and the variable $vardir is equal to the null string:

DB<15> b 12 ($vardir eq "")

Any legal Perl conditional expression can be specified with the b statement.

[Sep 12, 2020] Persistent syntax errors such as missing semicolon, missing closing brace and unclosed literal.

Sep 12, 2020 | www.sciencedirect.com

https://www.sciencedirect.com/science/article/abs/pii/0096055178900413

A statistical analysis of syntax errors - ScienceDirect

For example, approximately one-fourth of all original syntax errors in the Pascal sample were
missing semicolons or use of comma in place of semicolon 4) indicates that this type of error
is quite infrequent (80o) and hence needn't be of as great a concern to recovery pro

[PDF] Error log analysis in C programming language courses [BOOK] Programming languages JJ Horning - 1979 - books.google.com to note that over 14% of the faults occurring in topps programs during the second half of the
experiment were still semicolon faults (compared to 1% for toppsii), and that missing semicolons
were about Every decision takes time, and provides an opportunity for error n assessment of locally least-cost error recovery SO Anderson, RC Backhouse , EH Bugge - The Computer , 1983 - academic.oup.com sym = semicolon in the former, one is anticipating the possibility of a missing semicolon ; in contrast,
a missing comma is 13, p. 229) if sy = semicolon then insymbol else begin error (14); if sy = comma
then insymbol end Both conditional statements accept semicolons but the The role of systematic errors in developmental studies of programming language learners J Segal, K Ahmad , M Rogers - Journal of Educational , 1992 - journals.sagepub.com Errors were classified by their surface characteristics into single token ( missing gathered from
the students, was that they would experience considerable difficulties with using semicolons ,
and that the specific rule of ALGOL 68 syntax concerning the role of the semicolon as a Cited by 9 Related articles Follow set error recovery C Stirling - Software: Practice and Experience, 1985 - Wiley Online Library Some accounts of the recovery scheme mention and make use of non- systematic changes to
their recursive descent parsers in order to improve In the former he anticipates the possibility of
a missing semicolon whereas in the latter he does not anticipate a missing comma A first look at novice compilation behaviour using BlueJ MC Jadud - Computer Science Education, 2005 - Taylor & Francis or mark themselves present from weeks previous they may have missed -- either way change
programmer behaviour -- perhaps encouraging them to make fewer " missing semicolon " errors ,
or be or perhaps highlight places where semicolons should be when they are missing Making programming more conversational A Repenning - 2011 IEEE Symposium on Visual Languages , 2011 - ieeexplore.ieee.org Miss one semicolon in a C program and the program may no longer work at all Similar to code
auto-completion approaches, these kinds of visual programming environments prevent syntactic
programming mistakes such as missing semicolons or typos

[Aug 27, 2020] Rubber Duck Debugging

Notable quotes:
"... Original Credit ..."
Aug 27, 2020 | rubberduckdebugging.com

The rubber duck debugging method is as follows:

  1. Beg, borrow, steal, buy, fabricate or otherwise obtain a rubber duck (bathtub variety).
  2. Place rubber duck on desk and inform it you are just going to go over some code with it, if that's all right.
  3. Explain to the duck what your code is supposed to do, and then go into detail and explain your code line by line.
  4. At some point you will tell the duck what you are doing next and then realise that that is not in fact what you are actually doing. The duck will sit there serenely, happy in the knowledge that it has helped you on your way.

Note : In a pinch a coworker might be able to substitute for the duck, however, it is often preferred to confide mistakes to the duck instead of your coworker.

Original Credit : ~Andy from lists.ethernal.org

FAQs 4 days ago

I'd also highly recommend this chapter on debugging from Think Python book: https://greenteapress.com/thinkpython2/html/thinkpython2021.html

and this article: https://jvns.ca/blog/2019/06/23/a-few-debugging-resources/

[Aug 21, 2020] debugging - Can the Perl debugger save the ReadLine history to a file

Jan 01, 2011 | stackoverflow.com

Ask Question Asked 9 years, 2 months ago Active 6 years, 9 months ago Viewed 995 times Bright futures begin at Lutron View all 4 job openings!


bitbucket , 2011-06-21 23:35:26

I work quit a bit with lib ReadLine and the lib Perl Readline.

Yet, the Perl debugger refuses to save the session command line history.

Thus, each time I invoke the debugger I lose all of my previous history.

Does anyone know how to have the Perl debugger save, and hopefully, append session history similar to the bash HISTORYFILE ?

eli ,

just for anyone else looking for that: for readline to work in perl (ctrl-p / ctrl-n / ...) one has to apt-get install libterm-readline-gnu-perl (at least in debian) – eli Jun 7 '18 at 14:13

ysth ,

The way I do this is by having the following line in my ~/.perldb file:

&parse_options("HistFile=$ENV{HOME}/.perldb.hist");

Debugger commands are then stored in ~/.perldb.hist and accessible across sessions.

ysth ,

@bitbucket: I've had enough problems in the past getting the built-in readline support working that I don't even bother anymore :) – ysth Jun 22 '11 at 16:59

[Nov 21, 2019] Replaying debugger commands from history

Nov 21, 2019 | perlmonks.org

LanX (Archbishop) on Nov 20, 2019 at 15:59 UTC

Re: Replaying debugger commands from history

Sure!

Have a look at the docs in perldebug#Debugger-Customization concerning

@DB::typeahead

like

sub afterinit { push @DB::typeahead, "b 4", "b 6"; }

IIRC it should be either settable

[Nov 21, 2019] Can the Perl debugger save the ReadLine history to a file?

Nov 21, 2019 | stackoverflow.com

Ask Question Asked 8 years, 5 months ago Active 6 years ago Viewed 941 times 10 2


eli ,Jun 7, 2018 at 14:13

I work quit a bit with lib ReadLine and the lib Perl Readline.

Yet, the Perl debugger refuses to save the session command line history.

Thus, each time I invoke the debugger I lose all of my previous history.

Does anyone know how to have the Perl debugger save, and hopefully, append session history similar to the bash HISTORYFILE ?

mirod ,Jun 22, 2011 at 10:31

The way I do this is by having the following line in my ~/.perldb file:

&parse_options("HistFile=$ENV{HOME}/.perldb.hist");

Debugger commands are then stored in ~/.perldb.hist and accessible across sessions.

ysth ,Jul 13, 2011 at 9:37

Add parse_options("TTY=/dev/stdin ReadLine=0"); to .perldb, then:
rlwrap -H .perl_history perl -d ...

mephinet ,Feb 21, 2012 at 12:37

$ export PERLDB_OPTS=HistFile=$HOME/.perldb.history

,

I did the following:

1) Created ~/.perldb , which did not exist previously.

2) Added &parse_options("HistFile=$ENV{HOME}/.perldb.hist"); from mirod's answer.

3) Added export PERLDB_OPTS=HistFile=$HOME/.perldb.history to ~/.bashrc from mephinet's answer.

4) Ran source .bashrc

5) Ran perl -d my program.pl , and got this warning/error

perldb: Must not source insecure rcfile /home/ics/.perldb.
        You or the superuser must be the owner, and it must not 
        be writable by anyone but its owner.

6) I protected ~/.perldb with owner rw chmod 700 ~/.perldb , and the error went away.

[Nov 13, 2019] Static code analysis module in Perl - Stack Overflow

Nov 13, 2019 | stackoverflow.com

Static code analysis module in Perl Ask Question Asked 7 years, 5 months ago Active 1 year, 7 months ago Viewed 835 times 0

DavidO ,Jun 12, 2012 at 9:13

Is there any static code analysis module in Perl except B::Lint and Perl::Critic? How effective is Module::Checkstyle?

> ,

There is a post on perlmonks.org asking if PPI can be used for static analysis. PPI is the power behind Perl::Critic, according to the reviews of this module. (I have not used it yet).

Then there is perltidy .

[Nov 12, 2019] lib-Module-Checkstyle.pm

Nov 12, 2019 | metacpan.org

Module::Checkstyle is a tool similar to checkstyle http://checkstyle.sourceforge.net for Java. It allows you to validate that your code confirms to a set of guidelines checking various things such as indentation, naming, whitespace, complexity and so forth.

Module::Checkstyle is also extensible so your organization can implement custom checks that are not provided by the standard distribution. There is a guide on how to write checks in Module::Checkstyle::Check

Module::Checkstyle is mostly used via the provided module-checkstyle tool. You probablly want to read module-checkstyle .

NAME

module-checkstyle - Check that your code keeps style

SYNOPSIS

module-checkstyle [options] [file and directories ...]

This program is the command-line interface to Module::Checkstyle .

You invoke it by supplying a list of files or directories that contain Perl code that should be checked aginst the configuration. Any problems found will be reported on standard out.

OPTIONS
-help
Print a brief help message and exits.
-man
Prints the manual page and exists.
-config
Use an alternate config file instead of ~/.module-checkstyle/config .
-all
Don't ignore common files when traversing directories. Common files are things such as blib/* t/* Makefile.PL etc.
-debug
Turn on debugging information.
-version
Display version information.

[Nov 12, 2019] Static code analysis module in Perl - Stack Overflow

Nov 12, 2019 | stackoverflow.com

Static code analysis module in Perl Ask Question Asked 7 years, 5 months ago Active 1 year, 7 months ago Viewed 835 times 0

DavidO ,Jun 12, 2012 at 9:13

Is there any static code analysis module in Perl except B::Lint and Perl::Critic? How effective is Module::Checkstyle?

> ,

There is a post on perlmonks.org asking if PPI can be used for static analysis. PPI is the power behind Perl::Critic, according to the reviews of this module. (I have not used it yet).

Then there is perltidy .

[Nov 12, 2019] lib-Module-Checkstyle.pm - metacpan.org

Nov 12, 2019 | metacpan.org

Module::Checkstyle is a tool similar to checkstyle http://checkstyle.sourceforge.net for Java. It allows you to validate that your code confirms to a set of guidelines checking various things such as indentation, naming, whitespace, complexity and so forth.

Module::Checkstyle is also extensible so your organization can implement custom checks that are not provided by the standard distribution. There is a guide on how to write checks in Module::Checkstyle::Check

Module::Checkstyle is mostly used via the provided module-checkstyle tool. You probablly want to read module-checkstyle .

NAME

module-checkstyle - Check that your code keeps style

SYNOPSIS

module-checkstyle [options] [file and directories ...]

This program is the command-line interface to Module::Checkstyle .

You invoke it by supplying a list of files or directories that contain Perl code that should be checked aginst the configuration. Any problems found will be reported on standard out.

OPTIONS
-help
Print a brief help message and exits.
-man
Prints the manual page and exists.
-config
Use an alternate config file instead of ~/.module-checkstyle/config .
-all
Don't ignore common files when traversing directories. Common files are things such as blib/* t/* Makefile.PL etc.
-debug
Turn on debugging information.
-version
Display version information.

[Sep 24, 2019] warn - perldoc.perl.org

Sep 24, 2019 | perldoc.perl.org

Perl 5 version 30.0 documentation warn Perl functions A-Z | Perl functions by category | The 'perlfunc' manpage

[Sep 16, 2019] https://www.dummies.com/programming/perl/avoiding-common-oversights-in-perl/

Sep 16, 2019 | www.dummies.com

Avoiding Common Oversights in Perl

Related Book

Perl For Dummies, 4th Edition

By Paul Hoffman

Entering a typo or two during the course of writing a Perl program is not uncommon. But when you attempt to run a program containing a text-entry slip-up, Perl usually becomes confused and tells you so by reporting an error. The natural reaction for most people, even those with years of programming experience, is to get worried or angry or both when an error message pops up.

Don't panic. Take a deep breath. Take another slow, deep breath. Seriously, you can't get to the root of the problem if you're all tense and bothered. No matter how many years you program, you always end up finding some errors in the code you're written.

So, now that you are (hopefully!) a bit calmer, you can start to appreciate the fact that Perl has more helpful error messages than almost any other programming language. The messages aren't always right on the money, but they can get you pretty close to the spot where the problem lies with minimal searching on your part.

Perl has myriad error messages, but a few definitely crop up more than others owing to some common typos that everyone seems to make. The following errors result from minor text-entry goofs that you can easily avoid.

Forgetting a semicolon

Probably the most common error message you see when programming in Perl looks something like this:

# syntax error, near "open"
File 'counter1.pl'; Line 10
# Execution aborted due to compilation errors.

You can look and look at Line 10, the one with the open statement, and you won't see anything wrong with it. The trick here is to examine the statement that comes before the open statement and see whether it ends with a semicolon. (Perl knows that a statement ends only when it encounters a semicolon.) In this case, the error is caused by a missing semicolon at the end of Line 7 of the program:

$TheFile = "sample.txt"

Forgetting a quotation mark

The following sort of error message can be extremely frustrating if you don't know of a quick fix:

# Bare word found where operator expected, near
# "open(INFILE, $TheFile) or die "The"
# (Might be a runaway multi-line " string starting on
# line 7)
File 'counter1.pl'; Line 10

This error is similar to forgetting a semicolon; instead, it's a quotation mark that's accidentally omitted:

$TheFile = "sample.txt;

In this case, Perl did a good job of guessing what is wrong, suggesting that a runaway multi-line " string on Line 7 is the problem, which is precisely right.

Entering one parenthesis too many or too few

When you have loads of opening and closing parentheses in a program, it's easy to slip an extra one in by accident. If that's the case, you may see a message from Perl that reads something like this:

# syntax error, near ") eq"
File 'counter1.pl'; Line 38
# syntax error, near "}"
File 'counter1.pl'; Line 42

Here, Perl can't determine where the error is exactly, but it actually got it right on the first guess: Line 38 contains an extra right parenthesis:

if(substr($TheLine, $CharPos, 1)) eq " ")

Having one parenthesis too few in a Perl program can cause harder-to-find problems:

# Can't use constant item as left arg of implicit -- >,
# near "1 }"
File 'counter1.pl'; Line 39
# Scalar found where operator expected, near "$CharPos"
File 'counter1.pl'; Line 40
# (Missing semicolon on previous line?)
# syntax error, near "$CharPos "
File 'counter1.pl'; Line 40

Yarp! All this was produced because the last parenthesis on Line 38 is missing:

if(substr($TheLine, $CharPos, 1) eq " "

Here is another good lesson in hunting down typing errors: Start where Perl says it found an error. If you don't find the error there, go up a line or two and see if the problem started earlier.

A final word of advice: Trust Perl to find the simple typos for you (where it can), and remember that it's giving you all the help it can, which is more than you can say for many programming languages.

[Sep 10, 2019] Pro Perl Debugging

May 12, 2012 | Slashdot

This title was published in hardcover in March 2005 by Apress, a relatively new member of the technical publishing world. The publisher has a Web page for the book that includes links to all of the source code in a Zip file, the table of contents in PDF format, and a form for submitting errata. The book comprises 269 pages, the majority of which are organized into 16 chapters:

Introduction (not to be confused with the true Introduction immediately preceding it),

Inspecting Variables and Getting Help, Controlling Program Execution, Debugging a Simple Command Line Program, Tracing Execution, Debugging Modules, Debugging Object-Oriented Perl, Using the Debugger As a Shell, Debugging a CGI Program, Perl Threads and Forked Processes, Debugging Regular Expressions, Debugger Customization, Optimization and Performance Hints and Tips, Command Line and GUI Debuggers, Comprehensive Command Reference, Book References and URLs.

hattmoward ( 695554 ) , Monday December 12, 2005 @02:11PM ( #14240507 )

Re:In defense of print statements ( Score: 5 , Insightful)

How many times is that conditional checked at runtime? They can add up. In perl, you could have it optimized away at compile time...

sub DEBUG() { return 1; }

...

DEBUG and print "value of blah:", $blah, $/;

but... TIMTOWTDI ;)
Mark_Uplanguage ( 444809 ) , Monday December 12, 2005 @03:13PM ( #14241006 )
Re:In defense of print statements ( Score: 4 , Informative)

When debugging I emphasize the use of "warn" over "print". It's the same syntax, but the warn statements don't get spooled and therefore their timing is quicker.

This is vital when you code just plain blows up. Using "print" means that a statement which got executed before the disaster may not make it to console, thus leading you to believe that it never got executed. "warn" avoids this problem and thus leads you to the problem more accurately. It also makes it easy to globally comment out the warn statements before going releasing the code.

codyk ( 857932 ) , Monday December 12, 2005 @03:20PM ( #14241071 )
Re:In defense of print statements ( Score: 1 )

Or you could just . . .

use Smart::Comments;
### Expected: "a bunch o stuff" Got: $stuff

. . . and have debugging statements that are easier to write, can be turned off in one place, and don't waste efficiency checking a bunch of conditionals.
see http://search.cpan.org/~dconway/Smart-Comments-1. 0 .1/lib/Smart/Comments.pm [cpan.org]

licamell ( 778753 ) * , Monday December 12, 2005 @01:47PM ( #14240302 )
use strict and Data::Dumper! ( Score: 5 , Insightful)

#! /usr/local/bin/perl
#
# Two things that make debugging perl easy:
#

use strict;
use Data::Dumper; ›

Baron von Leezard ( 675918 ) , Monday December 12, 2005 @03:22PM ( #14241092 )
Re:use strict and Data::Dumper! ( Score: 1 )

[That's one freelance Perl programmer I'll have to remember never to hire.]

Seriously, I'm one of those people who use a debugger every day. Actually, when I write new code in Perl, often the first thing I do is step through it in the debugger to make sure it does what I think it should. Especially in Perl, it is very easy to accidentally do something that's a little off. With the "wait until something goes wrong before I investigate" attitude demonstrated here, you'll never know anything is amiss until some nasty bug crops up as a result. Using the debugger to sanity check my code means that I catch most bugs before they ever cause problems.

I'm sure I'm going to get some snide remarks about this approach, but really, I've been a serious Perl programmer for about eight years now, and often write moderately complex Perl programs that work perfectly the first time--run through the debugger or not. I can't say that about any other language, and it's something most people can't say about any language, let alone Perl ;)

[Aug 27, 2019] How do I get the filename and line number in Perl - Stack Overflow

Aug 27, 2019 | stackoverflow.com

How do I get the filename and line number in Perl? Ask Question Asked 8 years, 10 months ago Active 8 years, 9 months ago Viewed 6k times 6


Elijah ,Nov 1, 2010 at 17:35

I would like to get the current filename and line number within a Perl script. How do I do this?

For example, in a file call test.pl :

my $foo = 'bar';
print 'Hello World';
print functionForFilename() . ':' . functionForLineNo();

It would output:

Hello World
test.pl:3

tchrist ,Nov 2, 2010 at 19:13

These are available with the __LINE__ and __FILE__ tokens, as documented in perldoc perldata under "Special Literals":

The special literals __FILE__, __LINE__, and __PACKAGE__ represent the current filename, line number, and package name at that point in your program. They may be used only as separate tokens; they will not be interpolated into strings. If there is no current package (due to an empty package; directive), __PACKAGE__ is the undefined value.

Eric Strom ,Nov 1, 2010 at 17:41

The caller function will do what you are looking for:
sub print_info {
   my ($package, $filename, $line) = caller;
   ...
}

print_info(); # prints info about this line

This will get the information from where the sub is called, which is probably what you are looking for. The __FILE__ and __LINE__ directives only apply to where they are written, so you can not encapsulate their effect in a subroutine. (unless you wanted a sub that only prints info about where it is defined)

,

You can use:
print __FILE__. " " . __LINE__;

[Aug 26, 2019] Beginning Perl Programming From Novice to Professional

Aug 26, 2019 | www.amazon.com

Debugger Commands The debugger has many built-in commands. The most common are as follows.

Command

Meaning

!! cmd

Runs the command (cmd) in a separate process (this is typically a shell command)

h

Interactive help

H -num

Prints last "num" commands (excludes single character commands)

l

Lists the next line of code to be executed

n

Steps through a statement (if subroutines are called, executes over the subroutine)

q

Quits the debugger

s

Steps through a statement (if subroutines are called, executes one subroutine statement at a time)

V

Displays all of the variables in package (defaults to main)

[Aug 26, 2019] debugging - How can I debug a Perl script - Stack Overflow

Jun 27, 2014 | stackoverflow.com

Matthew Lock ,Jun 27, 2014 at 1:01

To run your script under perl debugger you should use -d switch:
perl -d script.pl

But perl is flexible. It supply some hooks and you may force debugger to work as you want

So to use different debuggers you may do:

perl -d:DebugHooks::Terminal script.pl
# OR
perl -d:Trepan script.pl

Look these modules here and here

There are several most interesting perl modules that hook into perl debugger internals: Devel::NYTProf , Devel::Cover

And many others

XXX,

If you want to do remote debug (for cgi or if you don't want to mess output with debug command line) use this:

given test:

use v5.14;
say 1;
say 2;
say 3;

Start a listener on whatever host and port on terminal 1 (here localhost:12345):

$ nc -v -l localhost -p 12345

for readline support use rlwrap (you can use on perl -d too):

$ rlwrap nc -v -l localhost -p 12345

And start the test on another terminal (say terminal 2):

$ PERLDB_OPTS="RemotePort=localhost:12345" perl -d test

Input/Output on terminal 1:

Connection from 127.0.0.1:42994

Loading DB routines from perl5db.pl version 1.49
Editor support available.

Enter h or 'h h' for help, or 'man perldebug' for more help.

main::(test:2): say 1;
  DB<1> n
main::(test:3): say 2;
  DB<1> select $DB::OUT

  DB<2> n
2
main::(test:4): say 3;
  DB<2> n
3
Debugged program terminated.  Use q to quit or R to restart,
use o inhibit_exit to avoid stopping after program termination,
h q, h R or h o to get additional info.  
  DB<2>

Output on terminal 2:

1

Note the sentence if you want output on debug terminal

select $DB::OUT

If you are vim user, install this plugin: dbg.vim which provides basic support for perl

[Aug 26, 2019] D>ebugging - How to use the Perl debugger

Aug 26, 2019 | stackoverflow.com
This is like "please can you give me an example how to drive a car" .

I have explained the basic commands that you will use most often. Beyond this you must read the debugger's inline help and reread the perldebug documentation

The debugger will do a lot more than this, but these are the basic commands that you need to know. You should experiment with them and look at the contents of the help text to get more proficient with the Perl debugger

[Dec 21, 2017] Common Syntax Errors

Dec 21, 2017 | affy.blogspot.com

One very common error is to use elseif instead of the correct elsif keyword. As you program, you'll find that you consistently make certain kinds of errors. This is okay. Everyone has his or her own little quirks. Mine is that I keep using the assignment operator instead of the equality operator. Just remember what your particular blind spot is. When errors occur, check for your personal common errors first.

This section shows some common syntax errors and the error messages that are generated as a result. First, the error message is shown and then the script that generated it. After the script, I'll cast some light as to why that particular message was generated.

Missing semiconon in one of the statements

Scalar found where operator expected at test.pl line 2, near "$bar"
        (Missing semicolon on previous line?)
$foo = { }    # this line is missing a semi-colon.
$bar = 5;
Perl sees the anonymous hash on the first line and is expecting either an operator or the semicolon to follow it. The scalar variable that it finds, $bar , does not fit the syntax of an expression because two variables can't be right after each other. In this case, even though the error message indicates line 2, the problem is in line 1.

Missing quote

Bare word found where operator expected at
    test.pl line 2, near "print("This"
  (Might be a runaway multi-line "" string starting on line 1)
syntax error at test.pl line 2, near "print("This is "
String found where operator expected at test.pl line 3, near "print(""
  (Might be a runaway multi-line "" string starting on line 2)
        (Missing semicolon on previous line?)
Bare word found where operator expected at
    test.pl line 3, near "print("This"
String found where operator expected at test.pl line 3, at end of line
        (Missing operator before ");
?)
Can't find string terminator '"' anywhere before EOF at test.pl line 3.
print("This is a test.\n);    # this line is missing a ending quote.
print("This is a test.\n");
print("This is a test.\n");

In this example, a missing end quote has generated 12 lines of error messages! You really need to look only at the last one in order to find out that the problem is a missing string terminator. While the last error message describes the problem, it does not tell you where the problem is. For that piece of information, you need to look at the first line where it tells you to look at line two. Of course, by this time you already know that if the error message says line 2, the error is probably in line 1.

Unquoted literal

Can't call method "a" in empty package "test" at test.pl line 1.
print(This is a test.\n);    # this line is missing a beginning quote.

The error being generated here is very cryptic and has little to do with the actual problem. In order to understand why the message mentions methods and packages, you need to understand the different, arcane ways you can invoke methods when programming with objects. You probably need to add a beginning quote if you ever see this error message.

... ... ..

This list of syntax errors could go on for quite a while, but you probably understand the basic concepts:

[Dec 20, 2017] Teach Yourself Perl 5 in 21 days - Table of Contents

Dec 20, 2017 | www.davetill.com

Chapter 21 The Perl Debugger


CONTENTS

Today's lesson describes the Perl debugging facility. You'll learn the following:

Entering and Exiting the Perl Debugger

The following sections describe how to start the Perl debugger and how to exit.

Entering the Debugger

To debug a Perl program, specify the -d option when you run the program. For example, to debug a program named debugtest , specify the following command:

$ perl -d debugtest

You can supply other options along with -d if you want to.

When the Perl interpreter sees the -d option, it starts the Perl debugger. The debugger begins by displaying a message similar to the following one on your screen:

Loading DB routines from $RCSfile: perldb.pl,v  $$Revision: 4.0.1.3

$$Date: 92/06/08 13:43:57 $

Emacs support available.



Enter h for help.



main::(debugtest:3):        $dircount = 0;

  DB<1>

The first few lines display the date on which this version of the debugger was created. The only lines of interest are the last two.

The second-to-last line in this display lists the line that the debugger is about to execute. When the debugger starts, the first executable line of the program is displayed.

When the debugger displays a line that it is about to execute, it also provides the following information about the line:

The last line of the display prompts you for a debugging command. The number enclosed in angle brackets indicates the command number; in this case, the number is 1 , because you are about to specify the first debugging command.

Later today you will learn how to use the debugging command number to re-enter debugging commands you have previously executed.

NOTE
To enter the debugger without supplying a program, supply the -e option with the -d option:
$ perl -d -e "1;"
This line starts the debugger with a "program" consisting of the single statement
1;
(which is an expression that doesn't do anything meaningful).
Starting the debugger without a program enables you to examine the predefined system variables or supply statements to be executed. You will learn how to perform both of these tasks later in today's lesson
Exiting the Debugger

To exit the debugger, enter the debugging command q :

DB<1> q

This command halts program execution immediately and returns you to the command shell.

Listing Your Program

You can list any part of your program from within the debugger. The following sections describe debugging commands that perform the display operations.

The command

The simplest way to list part of your program is with the l command, which lists the next few statements in your program:

  DB<1> l

3:      $dircount = 0;

4:      $curdir = "";

5:      while (1) {

6:              # if we don't have a current directory, get one

7:              if ($curdir eq "") {

8:                      print ("Enter directory to list:\n");

9:                      $curdir = <STDIN>;

10:                     $curdir =~ s/^\s+|\s+$//g;

11:                     $curdir = &followlink($curdir);

12:                     &readsubdirs($curdir);

The l command lists a window of executable statements, which is a group of statements small enough to be easily displayed on your screen. A window usually consists of about ten statements. The line number of each statement is displayed at the beginning of its line.

NOTE
The statements displayed in today's lesson are taken from the program presented in "Week 2 in Review."

Entering the l command again displays the window of statements immediately following the last displayed line, which in this example is line 12:

  DB<1> l

13:             }

14:             $curdir = &menudir($curdir);

15:     }

16:

17:

18:     # Find all subdirectories of the given directory,

19:     # and store them in an associative array.

20:     #

21:     # The associative array subscripts and values are:

22:     # <directory name>:       1

You can specify the lines displayed by the l command. If you specify a single line number with the l command, it displays that line:

  DB<1> l 10

10:                      $curdir =~ s/^\s+|\s+$//g;

To display a range of lines, specify the first and last line number, and separate them with a hyphen:

  DB<1> l 10-15

10:                      $curdir =~ s/^\s+|\s+$//g;

11:                      $curdir = &followlink($curdir);

12:                      &readsubdirs($curdir);

13:             }

14:             $curdir = &menudir($curdir);

15:     }

To display a specified number of lines starting at a certain point, supply the starting line number, a + character, and a number of additional lines to display:

  DB<1> l 10+5

10:                      $curdir =~ s/^\s+|\s+$//g;

11:                      $curdir = &followlink($curdir);

12:                      &readsubdirs($curdir);

13:             }

14:             $curdir = &menudir($curdir);

15:     }

You also can use the l command to specify a subroutine to display. To do this, provide the name of the subroutine to display:

  DB<1> l readsubdirs

26:     sub readsubdirs {

27:             local ($dirname) = @_;

28:             local ($dirvar, $subdircount, $name, $index);

29:

30:             # open the current directory;

31:             # $dircount ensures that each file variable is unique

32:             $dirvar = "DIR" . ++$dircount;

33:             if (!opendir ($dirvar, $dirname)) {

34:                     warn ("Can't open $dirname\n");

35:                     return;

This command lists the statements in the subroutine. If the subroutine is too large to fit in a single window, only the first few statements are listed; you can list subsequent statements by entering l with no arguments.

The Command

You can display the lines immediately preceding the last displayed line by entering the - command. For example, the following - command lists the window of lines immediately preceding the subroutine readsubdirs .

  DB<1> -

16:

17:

18:     # Find all subdirectories of the given directory,

19:     # and store them in an associative array.

20:     #

21:     # The associative array subscripts and values are:

22:     # <directory name>:       1

23:     #       (indicates that directory has been read)

24:     # <directory name>.<num>  the <num>th subdirectory

25:

Subsequent - commands go back further in the file.

The Command

To list a window of lines containinga specified line, use the w command, and specify the number of the line to be included:

  DB<1> w 7

4:      $curdir = "";

5:      while (1) {

6:              # if we don't have a current directory, get one

7:              if ($curdir eq "") {

8:                      print ("Enter directory to list:\n");

9:                      $curdir = <STDIN>;

10:                     $curdir =~ s/^\s+|\s+$//g;

11:                     $curdir = &followlink($curdir);

12:                     &readsubdirs($curdir);

13:             }

The w command displays the three lines before the specified line and fills the window with the lines following it.

The // and ?? Commands

You can search for a line containing a particular pattern by enclosing the pattern in slashes:

  DB<1> /Find/

18:     # Find all subdirectories of the given directory,

The debugger searches forward from the last displayed line for a line matching the specified pattern. If it finds such a line, the line is displayed.

To search backward for a particular pattern, enclose the pattern in question marks:

  DB<1> ?readsubdirs?

12:                      &readsubdirs($curdir);

This command starts with the last displayed line and searches backward until it finds a line matching the specified pattern.

NOTE
Patterns specified by // and ?? can contain any special character understood by the Perl interpreter.
You optionally can omit the final / or ? character when you match a pattern.
The Command

The S command lists all the subroutines in the current file, one subroutine per line:

  DB<> S

main::display

main::followlink

main::menudir

main::readsubdirs

Each subroutine name is preceded by the package name and a single quotation mark.

Stepping Through Programs

One of the most useful features of the Perl debugger is the capability to execute a program one statement at a time. The following sections describe the statements that carry out this action.

The Command

To execute a single statement of your program, use the s command:

  DB<2> s

main::(debugtest:4):        $curdir = "";

This command executes one statement of your program and then displays the next statement to be executed. If the statement executed needs to read from the standard input file, the debugger waits until the input is provided before displaying the next line to execute.

TIP
If you have forgotten which line is the next line to execute (because, for example, you have displayed lines using the l command), you can list the next line to execute using the L command:
DB<2> L
3: $dircount = 0;
The L command lists the last lines executed by the program. It also lists any breakpoints and line actions that have been defined for particular lines. Breakpoints and line actions are discussed later today.

If the statement executed by the s command calls a subroutine, the Perl debugger enters the subroutine but does not execute any statements in it. Instead, it stops at the first executable statement in the subroutine and displays it. For example, if the following is the current line:

main::(debugtest:12):                      &readsubdirs($curdir);

specifying the s command tells the Perl debugger to enter readsubdirs and display the following, which is the first executable line of readsubdirs :

main::readsubdirs(debugtest:27):      local ($dirname) = @_;

The s command assumes that you want to debug the subroutine you have entered. If you know that a particular subroutine works properly and you don't want to step through it one statement at a time, use the n command, described in the following section.

The Command

The n command, like the s command, executes one line of your program and displays the next line to be executed:

  DB<2> n

main::(debugtest:5):        while (1) {

The n statement, however, does not enter any subroutines. If the statement executed by n contains a subroutine call, the subroutine is executed in its entirety. After the subroutine is executed, the debugger displays the line immediately following the call.

For example, if the current line is

main::(debugtest:12):                      &readsubdirs($curdir);

the n command tells the debugger to execute readsubdirs and then display the next line in the program, which is

main::(debugtest:13:):             }

Combining the use of s and n ensures that the debugger examines only the subroutines you want to see.

NOTE
The Perl debugger does not enable you to enter any library functions. You can enter only subroutines that you have created yourself or that have been created previously and added to a subroutine library
The command

The f command tells the Perl debugger to execute the remainder of the statements in the current subroutine and then display the line immediately after the subroutine call. This is useful when you are looking for a bug and have determined that the current subroutine does not contain the problem.

The Carriage-Return Command

If you are stepping through a program using s or n , you can save yourself some typing by just pressing Enter when you want to execute another statement. When you press Enter, the debugger repeats the last s or n command executed.

For example, to step from line 5 to line 7, you can use the s command as usual:

  DB<3> s

main::(debugtest:7):              if ($curdir eq "") {

(Line 6 is skipped because it contains no executable statements.) To execute line 7, you can now just press Enter:

  DB<2>

main::(debugtest:8):              print ("Enter directory to list:\n");



NOTE
Pressing Enter has no effect if you have not specified any s or n commands.
The Command

If you are inside a subroutine and decide that you no longer need to step through it, you can tell the Perl debugger to finish executing the subroutine and return to the statement after the subroutine call. To do this, use the r command:

  DB<4> r

main::(debugtest:13:):             }

The statement displayed by the debugger is the first statement following the call to the subroutine.

Displaying Variable Values

Another powerful feature of the Perl debugger is the capability to display the value of any variable at any time. The following sections describe the commands that perform this action.

The Command

The X command displays variables in the current package (which is main if no other package has been specified). If the X command is specified by itself, it lists all the variables in the current package, including the system-defined variables and the variables used by the Perl interpreter itself. Usually, you won't want to use the X command by itself, because there are a lot of system-defined and internal variables known to the Perl interpreter.

To print the value of a particular variable or variables, specify the variable name or names with the X command:

  DB<5> X dircount

$dircount = '0'

This capability often is useful when you are checking for errors in your program.

You must not supply the $ character with the variable name when you use the X command. If you supply the $ character (or the @ or % characters for arrays), the debugger displays nothing.

You can use X to display the values of array variables and associative array variables.

  DB<6> X regarray

@regarray = (

  0     14

  1     'hello'

  2     36

)

  DB<7> X assocarray

%assoc_array = (

  'hi'  1

  'there' 2

)

Each command prints the subscripts of the array and their values. Regular arrays are printed in order of subscript; associative arrays are printed in no particular order.

NOTE
If you have an array variable and a scalar variable with the same name, the X command prints both variables:
DB<8> X var
$var = '0'
@var = (
0 'test1'
1 'test2'
)
There is no way to use X to display one variable but not the other.
The Command

The V command is identical to the X command except that it prints the values of variables in any package. If you specify just a package name, as in the following, this command displays the values of all variables in the package (including system-defined and internal variables):

DB<9> V mypack

If you specify a package name and one or more variable names, as in the following, the debugger prints the values of the variables (if they are defined in that package):

  DB<10> V main dircount

$dircount = '0'

Breakpoints

As you have seen, you can tell the Perl debugger to execute one statement at a time. Another way of controlling program execution is to tell the debugger to execute up to a certain specified point in the program, called a breakpoint .

The following sections describe the commands that create breakpoints, and the command that executes until a breakpoint is detected.

The Command

To set a breakpoint in your program, use the b command. This command tells the debugger to halt program execution whenever it is about to execute the specified line. For example, the following command tells the debugger to halt when it is about to execute line 10:

DB<11> b 10

(If the line is not breakable, the debugger will return Line 10 is not breakable .)

NOTE
You can have as many breakpoints in your program as you want. The debugger will halt program execution if it is about to execute any of the statements at which a breakpoint has been defined.

The b command also accepts subroutine names:

DB<12> b menudir

This sets a breakpoint at the first executable statement of the subroutine menudir .

You can use the b command to tell the program to halt only when a specified condition is true. For example, the following command tells the debugger to halt if it is about to execute line 10 and the variable $curdir is equal to the null string:

DB<12> b 10 ($curdir eq "")

The condition specified with the b statement can be any legal Perl conditional expression.

If a statement is longer than a single line, you can set a breakpoint only at the first line of the statement:
71: print ("Test",
72: " here is more output");
Here, you can set a breakpoint at line 71, but not line 72.
The Command

After you have set a breakpoint, you can tell the debugger to execute until it reaches either the breakpoint or the end of the program. To do this, use the c command:

  DB<13> c

main::(debugtest:10):                  $curdir =~ s/^\s+|\s+$//g;

  DB<14>

When the debugger detects that it is about to execute line 10-the line at which the breakpoint was set-it halts and displays the line. (Recall that the debugger always displays the line it is about to execute.)

The debugger now prompts you for another debugging command. This action enables you to start executing one statement at a time using n or s , continue execution using c , set more breakpoints using b , or perform any other debugging operation.

You can specify a temporary (one-time-only) breakpoint with the c command by supplying a line number:

  DB<15> c 12

main::(debugtest:12):                      &readsubdirs($curdir);

The argument 12 supplied with the c command tells the debugger to define a temporary breakpoint at line 12 and then resume execution. When the debugger reaches line 12, it halts execution, displays the line, and deletes the breakpoint. (The line itself still exists, of course.)

Using c to define a temporary breakpoint is useful if you want to skip a few lines without wasting your time executing the program one statement at a time. Using c also means that you don't have to bother defining a breakpoint using b and deleting it using d (described in the following section).

TIP
If you intend to define breakpoints using c or b , it is a good idea to ensure that each line of your program contains at most one statement. If you are in the habit of writing lines that contain more than one statement, such as
$x++; $y++;
you won't get as much use out of the debugger, because it can't stop in the middle of a line
The Command and Breakpoints

To list all of your breakpoints, use the L command. This command lists the last few lines executed, the current line, the breakpoints you have defined, and the conditions under which the breakpoints go into effect.

  DB<16> L

3:      $dircount = 0;

4:      $curdir = "";

5:      while (1) {

7:              if ($curdir eq "") {

10:                      $curdir =~ s/^\s+|\s+$//g;

  break if (1)

Here, the program has executed lines 3-7, and a breakpoint is defined for line 10. (Line 6 is not listed because it is a comment.) You can distinguish breakpoints from executed lines by looking for the breakpoint conditional expression, which immediately follows the breakpoint. Here, the conditional expression is (1) , which indicates that the breakpoint is always in effect.

The and Commands

When you are finished with a breakpoint, you can delete it using the d command.

DB<16> d 10

This command tells the debugger to delete the breakpoint at line 10. The line itself remains in the program.

If you do not specify a breakpoint to delete, the debugger assumes that a breakpoint is defined for the next line to be executed, and deletes it.

main::(debugtest:12):                      &readsubdirs($curdir);

  DB<17> d

Here, line 12 is the next line to be executed, so the debugger deletes the breakpoint at line 12.

To delete all your breakpoints, use the D command.

DB<18> D

This command deletes all the breakpoints you have defined with the b command.

Tracing Program Execution

When you run a program using the Perl debugger, you can tell it to display each line as it is executed. When the debugger is doing this, it is said to be in trace mode .

To turn on trace mode, use the T command.

  DB<18> t

Trace = on

When a statement is executed in trace mode, the statement is displayed. For example, if the current line is line 5 and the command c 10 (which executes up to line 10) is entered, the following is displayed:

  DB<18> c 10

main::(debugtest:5):      while (1) {

main::(debugtest:7):              if ($curdir eq "") {

main::(debugtest:10):                      $curdir =~ s/^\s+|\s+$//g;

  DB<19>

The debugger prints and executes line 5 and line 7, then displays line 10 and waits for further instructions.

To turn off trace mode, specify the t command again.

  DB<19> t

Trace = off

At this point, trace mode is turned off until another t command is entered.

Line Actions

The Perl debugger enables you to specify one or more statements to be executed whenever the program reaches a specified line. Such statements are known as line actions. The most common line actions are printing the value of a variable and resetting a variable containing an erroneous value to the value you want.

The following sections describe the debugging commands that define line actions.

The Command

To specify a line action for a particular line, use the a command.

DB<19> a 10 print ("curdir is $curdir\n");

This command tells the debugger to execute the statement

print ("curdir is $curdir\n");

whenever it is about to execute line 10 of the program. The debugger performs the action just after it displays the current line and before it asks for the next debugging command.

To create a line action containing more than one statement, just string the statements together. If you need more than one line for the statements, put a backslash at the end of the first line.

  DB<20> a 10 print ("curdir is $curdir\n"); print \

("this is a long line action\n");

In this case, when the debugger reaches line 10, it executes the following statements:

print ("curdir is $curdir\n");

print ("this is a long line action\n");

The Command

To delete the line actions defined using the a command, use the A command.

DB<21> A

This command deletes all line actions currently defined.

NOTE
The A command does not affect the < and > commands, described in the following section.
The < and > Commands

To define a line action that is to be executed before the debugger executes any further statements, use the > command.

DB<21> > print ("curdir before execution is $curdir\n");

This command tells the debugger to print the value of $curdir before continuing.

Similarly, the < command defines a line action that is to be performed after the debugger has finished executing statements and before it asks for another debugging command:

DB<22> < print ("curdir after execution is $curdir\n");

This command tells the debugger to print the value of $curdir before halting execution again.

The < and > commands are useful when you know that one of your variables has the wrong value, but you don't know which statement assigned the wrong value to the variable. By single-stepping through the program using s or n , and printing the variable either before or after executing each statement, you can determine where the variable was given its incorrect value.

NOTE
To delete a line action defined by the < command, enter another < command with no line action defined.
DB<23> <
Similarly, the following command undoes the effects of a > command:
DB<24> >
Displaying Line Actions Using the Command

The L command prints any line actions you have defined using the a command (as well as breakpoints and executed lines). For example, suppose that you have defined a line action using the following command:

DB<25> a 10 print ("curdir is $curdir\n");

The L command then displays this line action as shown here:

main::(debugtest:10):                      $curdir =~ s/^\s+|\s+$//g;

  action:  print ("curdir is $curdir\n");

The line action is always displayed immediately after the line for which it is defined. This method of display enables you to distinguish lines containing line actions from other lines displayed by the L command.

Other Debugging Commands

The following sections describe the debugging commands not previously covered.

Executing Other Perl Statements

In the debugger, anything that is not a debugging command is assumed to be a Perl statement and is performed right away. For example:

DB<4> @array = (1, 2, 3);

You can use statements such as this to alter values in your program as it is being executed. This capability is useful when you are testing your code.

NOTE
If you wish, you can omit the semicolon at the end of the statement.
The Command: Listing Preceding Commands

The H (for "history") command lists the preceding few commands you have entered.

  DB<4> H

3: b 7

2: b 14

1: b 13

The commands are listed in reverse order, with the most recently executed command listed first. Each command is preceded by its command number, which is used by the ! command (described in the following section).

NOTE
The debugger saves only the commands that actually affect the debugging environment. Commands such as l and s , which perform useful work but do not change how the debugger behaves, are not listed by the H command.
This is not a significant limitation because you can enter the letter again if needed.
The Command: Executing Previous Commands

Each command that is saved by the debugger and can be listed by the H command has a command number. You can use this command number to repeat a previously executed command. For example, to repeat command number 5, make the following entry:

  DB <11> !5

b 8

  DB <12>

The debugger displays command number 5-in this case, the command b 8 - and then executes it.

If you omit the number, the debugger repeats the last command executed.

  DB <12> $foo += $bar + 1

  DB <13> !

$foo += $bar + 1

  DB <14>

If you specify a negative number with ! , the debugger skips back that many commands:

  DB <14> $foo += $bar + 1

  DB <15> $foo *= 2

  DB <16> ! -2

$foo += $bar + 1

  DB <17>

Here, the ! -2 command refers to the command $foo += $bar + 1 .

You can use ! only to repeat commands that are actually repeatable. Use the H command to list the commands that the debugger has saved and that can be repeated
The Command: Stack Tracing

The T command enables you to display a stack trace, which is a collection of all the subroutines that have been called, listed in reverse order. Here is an example:

  DB <16> T

$ = &main::sub2('hi') from file debug1 line 7

$ = &main::sub1('hi') from file debug1 line 3

Here, the T command indicates that the program is currently inside subroutine sub2 , which was called from line 7 of your program; this subroutine is part of the main package. The call to sub2 is passed the argument 'hi' .

The $ = preceding the subroutine name indicates that the subroutine call is expecting a scalar return value. If the call is expecting a list to be returned, the characters @ = appear in front of the subroutine name.

The next line of the displayed output tells you that sub2 was called by another subroutine, sub1 . This subroutine was also passed the argument 'hi' , and it was called by line 3 of the program. Because the stack trace lists no more subroutines, line 3 is part of your main program.

NOTE
The list of arguments passed to a subroutine that is displayed by the stack trace is the list of actual values after variable substitution and expression evaluation are performed. This procedure enables you to use the stack trace to check whether your subroutines are being passed the values you expect.
The Command: Printing an Expression

An easy way to print the value of an expression from inside the debugger is to use the p command.

  DB <17> p $curdir + 1

1

The p command evaluates the expression and displays the result.

NOTE
The p command writes to the screen even when the program has redirected STDOUT to a file.
The Command: Defining Aliases

If you find yourself repeatedly entering a long debugging command and you want to save yourself some typing, you can define an alias for the long command by using the = command. For example:

  DB <15> = pc print ("curdir is $curdir\n");

= pc print ("curdir is $curdir\n");

The = command prints the alias you have just defined and then stores it in the associative array %DB'alias (package DB , array name alias ) for future reference. From here on, the command

DB <16> pc

is equivalent to the command

DB <16> print ("curdir is $curdir\n");

To list the aliases you have defined so far, enter the = command by itself:

  DB <17> =

pc =  print ("curdir is $curdir\n")

This command displays your defined aliases and their equivalent values.

Predefining Aliases

You can define aliases that are to be created every time you enter the Perl debugger.

When the debugger starts, it first searches for a file named .perldb in your home directory. If the debugger finds this file, it executes the statements contained there.

To create an alias, add it to the .perldb file. For example, to add the alias

= pc print ("curdir is $curdir\n");

add the following statement to your .perldb file:

$DB'alias{"pc"} = 's/^pc/print ("curdir is $curdir\n");/';

Here's how this works: when the Perl debugger creates an alias, it adds an element to the $DB'alias associative array. The subscript for this element is the alias you are defining, and the value is a substitution command that replaces the alias with the actual command you want to use. In the preceding example, the substitution takes any command starting with pc and replaces it with

print ("curdir is $curdir\n");


Be careful when you define aliases in this way. For example, your substitution should match only the beginning of a command, as in /^pc/ . Otherwise, the alias will replace any occurrence of the letters pc with your print command, which is not what you want.
The Command: Debugger Help

The h (for help) command provides a list of each of the debugger commands listed in today's lesson, along with a one-line explanation of each. This is handy if you are in the middle of debugging a program and forget the syntax of a particular command.

Summary

Today, you have learned about the Perl debugger. This debugger enables you to perform the following tasks, among others:

Q&A
Q: Is it possible to enter more than one debugging command at a time?
A: No; however, there's no real need to do so. If you want to perform several single steps at once, use the c command to skip ahead to a specified point. If you want to both step ahead and print the value of a variable, use the < or > command.
Q: Is it possible to examine variables in one package while inside another?
A: Yes. Use the V command or the standard Perl package/variable syntax.
Q: If I discover that my program works and I want to turn off debugging, what do I do?
A: You cannot exit the debugger in the middle of a program. However, if you delete all breakpoints and line actions and then enter the c command, the program begins executing normally and is no longer under control of the debugger.
Q: How can I convert to a reusable breakpoint a one-time breakpoint created using c ?
A: By default, the b command sets a breakpoint at the line that is about to be executed. This is the line at which c has set its one-time breakpoint.
Q: How can I execute other UNIX commands from inside the debugger?
A: Enter a statement containing a call to the Perl system function. For example, to display the contents of the current directory, enter the following command:
DB <11> system ("ls");
To temporarily escape from the debugger to a UNIX shell, enter the following command:
DB <12> system ("sh");
When you are finished with the shell, enter the command exit, and you will return to the debugger.
Q: What special built-in variables can be accessed from inside the debugger?
A: All of them.
Workshop

The Workshop provides quiz questions to help you solidify your understanding of the material covered.

Quiz
  1. Define the following terms:
    1. trace mode
    2. stack trace
    3. breakpoint
    4. line action
  1. Explain the differences between the X and V commands.
  2. Explain the differences between the // and ?? commands.
  3. Explain the differences between the < and > commands.
  4. Explain the differences between the s and n commands.
  5. What do the following commands do?
    1. l
    2. l 26
    3. l 5-7
    4. l 5+7
    5. w


[Dec 20, 2017] debugging - Can the Perl debugger save the ReadLine history to a file

Dec 20, 2017 | stackoverflow.com
The way I do this is by having the following line in my ~/.perldb file:

&parse_options("HistFile=$ENV{HOME}/.perldb.hist");

Debugger commands are then stored in ~/.perldb.hist and accessible across sessions.

I did the following:

1) Created ~/.perldb , which did not exist previously.

2) Added &parse_options("HistFile=$ENV{HOME}/.perldb.hist"); from mirod's answer.

3) Added export PERLDB_OPTS=HistFile=$HOME/.perldb.history to ~/.bashrc from mephinet's answer.

4) Ran source .bashrc

5) Ran perl -d my program.pl , and got this warning/error

perldb: Must not source insecure rcfile /home/ics/.perldb.
        You or the superuser must be the owner, and it must not 
        be writable by anyone but its owner.

6) I protected ~/.perldb with owner rw chmod 700 ~/.perldb , and the error went away.

[Dec 20, 2017] The Perl Debugger

Dec 20, 2017 | nnc3.com

Subroutines

There is one more variation of the list code command, l . It is the ability to list the code of a subroutine, by typing l sub , where sub is the subroutine name.

Running the code in Listing 2 returns:

Loading DB routines from perl5db.pl version 1
Emacs support available.
Enter h or h h for help.
main::(./p2.pl:3): require 5.001;
 DB<1>

Entering l searchdir allows us to see the text of searchdir , which is the meat of this program.

22 sub searchdir { # takes directory as argument
23: my($dir) = @_;
24: my(@files, @subdirs);
25
26: opendir(DIR,$dir) or die "Can't open \"
27:     $dir\" for reading: $!\n";
28
29: while(defined($_ = readdir(DIR))) {
30: /^\./ and next; # if file begins with '.', skip
31
32 ### SUBTLE HINT ###
As you can see, I left a subtle hint. The bug is that I deleted an important line at this point.

Setting Breakpoints

If we were to step through every line of code in a subroutine that is supposed to be recursive, it would take all day. As I mentioned before, the code as in Listing 2 seems only to list the files in the current directory, and it ignores the files in any subdirectories. Since the code only prints the files in the current, initial directory, maybe the recursive calls aren't working. Invoke the Listing 2 code under the debugger.

Now, set a breakpoint. A breakpoint is a way to tell the debugger that we want normal execution of the program until it gets to a specific point in the code. To specify where the debugger should stop, we insert a breakpoint. In the Perl debugger, there there are two basic ways to insert a breakpoint. The first is by line number, with the syntax b linenum . If linenum is omitted, the breakpoint is inserted at the next line about to be executed. However, we can also specify breakpoints by subroutine, by typing b sub , where sub is the subroutine name. Both forms of breakpointing take an optional second argument, a Perl conditional. If when the flow of execution reached the breakpoint the conditional evaluates to true, the debugger will stop at the breakpoint; otherwise, it will continue. This gives greater control of execution.

For now we'll set a break at the searchdir subroutine with b searchdir . Once the breakpoint is set, we'll just execute until we hit the subroutine. To do this, enter c (for continue). Adding Actions

Looking at the code in Listing 2, we can see that the first call to searchdir comes in the main code. This seems to works fine, or else nothing would be printed out. Press c again to continue to the next invocation of searchdir , which occurs in the searchdir routine.

We wish to know what is in the $dir variable, which represents the directory that will be searched for files and subdirectories. Specifically, we want to know the contents of this variable each time we cycle through the code. We can do this by setting an action. By looking at the program listing, we see that by line 25, the variable $dir has been assigned. So, set an action at line 25 in this way:

a 25 print "dir is $dir\n"

Now, whenever line 25 comes around, the print command will be executed. Note that for the a command, the line number is optional and defaults to the next line to be executed.

Pressing c will execute the code until we come across a breakpoint, executing action points that are set along the way. In our example, pressing c continuously will yield the following:

main::(../p2.pl:3): require 5.001;
 DB<1> b searchdir
 DB<2> a 25 print "dir is $dir\n"
 DB<3> c
main::searchdir(../p2.pl:23): my($dir) = @_;
 DB<3> c
dir is .
main::searchdir(../p2.pl:23): my($dir) = @_;
 DB<3> c
dir is dir1.0
main::searchdir(../p2.pl:23): my($dir) = @_;
 DB<3> c
dir is dir2.0
main::searchdir(../p2.pl:23): my($dir) = @_;
 DB<3> c
dir is dir3.0
file1
file1
file1
file1
DB::fake::(/usr/lib/perl5/perl5db.pl:2043):
2043: "Debugged program terminated. Use `q' to quit or `R' to
restart.";
 DB<3>

Note that older versions of the debugger don't output the last line as listed here, but instead exit the debugger. This newer version is nice because when the program has finished it still lets you have control so that you can restart the program.

It still seems that we aren't getting into any subdirectories. Enter D and A to clear all breakpoints and actions, respectively, and enter R to restart. Or, in older debugger versions, simply restart the program to begin again.

We now know that the searchdir subroutine isn't being called for any subdirectories except the first level ones. Looking back at the text of the program, notice in lines 44 through 46 that the only time the searchdir subroutine is called recursively is when there is something in the @subdirs list. Put an action at line 42 that will print the $dir and @subdirs variables by entering:

a 42 print "in $dir is @subdirs \n"

Now, put a breakpoint at line 12 to prevent the program from outputting to our screen ( b 12 ), then enter c . This will tell us all the subdirectories that our program thinks are in the directory.

main::(../p2.pl:3): require 5.001;
 DB<1> a 42 print "in $dir is @subdirs \n"
 DB<2> b 12
 DB<3> c
in . is dir1.0 dir2.0 dir3.0
in dir1.0 is
in dir2.0 is
in dir3.0 is
main::(../p2.pl:12): foreach (@files) {
 DB<3>
This program sees that there are directories in ".", but not in any of the subdirectories within ".". Since we are printing out the value of @subdirs at line 42, we know that @subdirs has no elements in it. (Notice that when listing line 42, there is the letter "a" after the line number and a colon. This tells us that there is an action point here.) So, nothing is being assigned to @subdirs in line 37, but should be if the current (as held in $_ ) file is a directory. If it is, it should be pushed into the @subdirs list. This is not happening.

One error I've committed (intentionally, of course) is on line 38. There is no catch-all "else" statement. I should probably put an error statement here. Instead of doing this, let's put in another action point. Reinitialize the program so that all points are cleared and enter the following:

a 34 if( ! -f $_ and ! -d $_ ) { print "in $dir: $_ is
weird!\n" }
b 12"
c

which reveals:

main::(../p2.pl:3): require 5.001;
 DB<1> a 34 if( ! -f $_ and ! -d $_ ) { print "in $dir:
$_ is weird!\n" }
 DB<2> b 12
 DB<3> c
in dir1.0: dir1.1 is weird!
in dir1.0: dir2.1 is weird!
in dir1.0: file2 is weird!
in dir1.0: file3 is weird!
in dir2.0: dir2.1 is weird!
in dir2.0: dir1.1 is weird!
in dir2.0: file2 is weird!
in dir2.0: file3 is weird!
main::(../p2.pl:12): foreach (@files) {
 DB<3>
While the program can read (through the readdir call on line 29) that dir1.1 is a file of some type in dir1.0, the file test (the -f construct) on dir1.1 says that it is not.

It would be nice to halt the execution at a point (line 34) where we have a problem. We can use the conditional breakpoint that I mentioned earlier to do this. Reinitialize or restart the debugger, and enter:

b 34 ( ! -f $_ and ! -d $_ )
c
p
p $dir

You'll get output that looks like this:

main::(../p2.pl:3): require 5.001;
 DB<1> b 34 ( ! -f $_ and ! -d $_ )
 DB<2> c
main::searchdir(../p2.pl:34): if( -f $_) { # if its a file...
 DB<2> p
dir1.1
 DB<2> p $dir
dir1.0
 DB<3>
The first line sets the breakpoint, the next c executes the program until the break point stops it. The p prints the contents of the variable $_ and the last command, p $dir prints out $dir . So, dir1.1 is a file in dir1.0, but the file tests ( -d and -f ) don't admit that it exists, and therefore dir1.1 is not being inserted into @subdirs (if it's a directory) or into @files (if it's a file).

Now that we are back at a prompt, we could inspect all sorts of variables, subroutines or any other Perl construct. To save you from banging your heads against your monitors, and thus saving both your heads and your monitors, I'll tell you what is wrong.

All programs have something known as the current working directory (CWD). By default, the CWD is the directory where the program starts. Any and all file accesses (such as file tests or file and directory openings) are made in reference from the CWD. At no time does our program change its CWD. But the values returned by the readdir call on line 29 are simply file names relative to the directory that readdir is reading (which is in $dir ). So, when we do the readdir , $_ gets assigned a string representing a file (or directory) within the directory in $dir (which is why it's called a subdirectory). But when running the -f and -d file tests, they look for $_ in the context of the CWD. But it isn't in the CWD, it's in the directory represented by $dir . The moral of the story is that we should be working with $dir/$_ , not just $_ . So the string

###SUBTLE HINT###

should be replaced by

$_ = "$dir/$_"; # make all path names absolute
That sums it up. Our problem was we were dealing with relative paths, not absolute (from the CWD) paths.

Putting it back into our example, we need to check dir1.0/dir1.1 , not dir1.1 . To check to make sure that this is what we want, we can put in another action point. Try typing:

a 34 $_ = "$dir/$_"
c

In effect this temporarily places the corrective measure into our code. Action points are the first item on the line to be evaluated. You should now see the proper results of the execution of the program:

DB<1> a 34 $_ = "$dir/$_"
DB<2> c
./file1
./dir1.0/file1
./dir1.0/file2
./dir1.0/file3
./dir1.0/dir1.1/file1
./dir1.0/dir1.1/file2
./dir1.0/dir1.1/file3
./dir2.0/file1
./dir2.0/file2
./dir2.0/file3
./dir2.0/dir2.1/file1
./dir2.0/dir2.1/file2
./dir3.0/file1
DB::fake::(/usr/lib/perl5/perl5db.pl:2043):
2043: "Debugged program terminated. Use `q' to quit or `R' to
restart.";
 DB<2>

Stack Traces

Now that we've got the recursive call debugged, let's play with the calling stack a bit. Giving the command T will display the current calling stack. The calling stack is a list of the subroutines which have been called between the current point in execution and the beginning of execution. In other words, if the main portion of the code executes subroutine "a", which in turn executes subroutine "b", which calls "c", then pressing "T" while in the middle of subroutine "c" outputs a list going from "c" all the way back to "main".

Start up the program and enter the following commands (omit the second one if you have fixed the bug we discovered in the last section):

b 34 ( $_ =~ /file2$/)
a 34 $_ = "$dir/$_"
c

These commands set a breakpoint that will only stop execution if the value of the variable $_ ends with the string file2 . Effectively, this code will halt execution at arbitrary points in the program. Press T and you'll get this:

@ = main::searchdir('./dir1.0/file2') called from file '../p2.pl' line
45
@ = main::searchdir(.) called from file '../p2.pl' line 10

Enter c , then T again:

@ = main::searchdir('./dir1.0/dir1.1/file2') called from file
`../p2.pl' line 45
@ = main::searchdir(undef) called from file '../p2.pl' line 45
@ = main::searchdir(.) called from file '../p2.pl' line 10

Do it once more:

@ = main::searchdir('./dir2.0/file2') called from file '../p2.pl' line
45
@ = main::searchdir(.) called from file '../p2.pl' line 10

You can go on, if you so desire, but I think we have enough data from the arbitrary stack dumps we've taken.

We see here which subroutines were called, the debugger's best guess of which arguments were passed to the subroutine and which line of which file the subroutine was called from. Since the lines begin with @ = , we know that searchdir will return a list. If it were going to return a scalar value, we'd see $ = . For hashes (also known as associative arrays), we would see % = .

I say "best guess of what arguments were passed" because in Perl, the arguments to subroutines are placed into the @_ magic list. However, manipulating @_ (or $_ ) in the body of the subroutine is allowed and even encouraged. When a T is entered, the stack trace is printed out, and the current value of @_ is printed as the arguments to the subroutine. So when @_ is changed, the trace doesn't reflect what was actually passed as arguments to the subroutine.

[Dec 20, 2017] Creating Command Aliases

Notable quotes:
"... You use the = command without any arguments when you want a list of the current aliases. ..."
Dec 20, 2017 | affy.blogspot.com

The = command is used to create command aliases. If you find yourself issuing the same long command over and over again, you can create an alias for that command. For example, the debugger command

= pFoo print("foo=$foo\n");
creates an alias called pFoo . After this command is issued, typing pFoo at the debugger prompt produces the same results as typing print("foo=$foo\n"); .

You use the = command without any arguments when you want a list of the current aliases.

If you want to set up some aliases that will always be defined, create a file called .perldb and fill it with your alias definitions. Use the following line as a template:

$DB::alias{'pFoo'} = 'print("foo=$foo\n");';
After you create this file and its alias definitions, the aliases will be available in every debugging session.

[Dec 20, 2017] Perl Debugger Quick Reference Card by Andrew Ford

Notable quotes:
"... in the current and home directories ..."
"... Any input to the debugger that is not recognized is executed as Perl code in the current package. ..."
Dec 20, 2017 | shinnok.com

Revision 0.1 for Perl Debugger version 5.8.x

Copyright: Andrew Ford refcards.com™

... ... ...

Debugger Commands

The debugger reads commands from the files .perldb in the current and home directories, and stops before the first run-time executable statement, displaying the line it is about to execute and a prompt:

DB<1>

If you run code from the debugger and hit another breakpoint, the prompt will look like DB"42". The numbers within the angle brackets are the command numbers, used when repeating commands.

Any input to the debugger that is not recognized is executed as Perl code in the current package.

Prefixing a command with ' | ' pipes the output to your current pager.

Help and Quiting

Debugger Control

... ... ...

[Dec 20, 2017] Chapter 30 -- Using the Perl Debugger

Dec 20, 2017 | ods.com.ua
... ... ... Looking at Values

To see the values of certain variables in the program, use the V command. Used by itself, V lists all the variables in scope at this time. Here's the syntax:

V [ package [ variable ]]

To look at values in your program, you'll want to look at the main package. For example, to print the value of $reply , use this command:

V main reply
$reply = '1'

Note that the dollar sign before the variable specified to V is not supplied. Therefore, if you specify the command V main $reply , you are actually asking for the value of $$reply and not $reply .

The trace option is available with the t toggle command. Issuing trace once turns it on, and issuing it again turns it off. See Figure 30.4 for a sample use of the trace command on Listing 30.2. In this example, trace is turned on, and then the c command is issued to run the debugger continuously. In trace mode, the debugger prints out each line of code that executes.

Figure 30.4 : Using the trace command with breakpoints.

The X command is helpful when displaying values of variables in the current package. Remember that the main package is the default package for a Perl script. Issued by itself with no options, the X command displays all the variables in the current package. Avoid issuing the X command by itself because it can generate a very long listing of all the variables in the main package.

To see the value of a particular variable instead of all the variables, type the name of the variable after the X command. For example, the following command

X fileNumber

will print the value of the fileNumber variable in the current package. If you have array variables and scalar variables with the same name in the same package, the X command will display the values of both these variables. For example, if you have a scalar variable called names and an array called names , the X command will show the values of both variables:

DB<3> X names
$names = "kamran"
@names = (
"kamran"
"joe"
"donald"
)
Breakpoints

You can place breakpoints at suspect locations in your code and run the program until one of the specified breakpoints is hit. Breakpoints can be specified to be hit as soon as the line of code is about to be executed.

The c command is used to step forward until either the program stops or a specified breakpoint is hit. To specify a breakpoint at the current line, use the b command without any parameters. To specify a specific line, use the command of the form:

b linenumber

Usually, you use trace statements to see statements between the current execution point and a breakpoint (refer to Figure 30.4). The program is run in continuous mode with the c command until it hits a breakpoint. There is a breakpoint in Listing 30.1 that causes the debugger to stop. The L command is issued in the example to list the breakpoints in the system.

Breakpoints can also be specified to occur at the first executable line of code within a subroutine. Simply use the b command with the name of the subroutine as the first parameter. For example, to break at the first line of code in the xyc subroutine, try this command:

b xyc

You can also ask the debugger to look at a condition when a line is hit with a breakpoint tag on it. If the breakpoint is specified at a line and the condition is true, the debugger stops; otherwise, it keeps on going. For example, if you want the debugger to stop in xyc only when the global $reply is 1 , use this command:

b xyc ($reply == '1')

To list all breakpoints defined during a debug session, use the L command. If you issue unconditional breakpoints, you'll see breakpoints listed as this:

break if (1)

The L command will also list up to the last five executed lines of the program.

To remove a breakpoint, use the d command and specify the line number to delete. To remove all breakpoints, use the D command. For example, to delete a breakpoint at line 12, you would issue the command d 12 .

The DB package uses the following sequence to hit breakpoints and evaluate code on each line of executable code:

  1. Checks to see whether the breakpoint is defined at this line number. If there is no breakpoint defined for this line, it starts to process the next line. If there is a break-
    point at this line, the debugger prepares to stop. If the condition for the defined breakpoint is true, the debugger stops execution and presents a prompt to the user.
  2. Checks to see whether the line of code is printable. If so, it prints the entire line of code (including code spanning multiple lines).
  3. Checks to see whether there are any actions defined for this line and performs these actions. (An action is a set of Perl commands to be executed.)
  4. Checks to see whether the stop was due to a breakpoint. If the condition for the breakpoint is true and a breakpoint has been marked in this location, the debugger stops and presents a prompt for user interaction.
  5. Evaluates the line and gets ready to execute it. Gets user input if the user is stopping; otherwise, it executes the line and returns to item 1 in order to process the next line.
Actions

You can specify actions to take when a certain line of code is executed. This step is very important when you want to print out values as the program executes (see Figure 30.5). Notice how the value of reply is printed out when line 73 is reached. The action is defined with this statement:

Figure 30.5 : Using actions in the debugger.

a 73 print "I am on line 73 and reply is $reply"

Notice that you did not have to terminate the action command with a semicolon. You need to use semicolons only if you have more than one statement for an action. If you forget to supply the terminating semicolon, the debugger will supply it for you. In any event, try to keep actions simple and short. Don't write lengthy actions unless absolutely necessary; otherwise, you'll slow down the debugger and clutter up the output on your terminal.

Actions are not limited to displaying values. For instance, you can use an action to reset a variable to a known value while in a loop, using a statement like this:

a 73 $reply = 1; print "forced reply to 1\n";

To execute statements within the debugged program's space, simply type the command at the prompt. For example, to explicitly create and set the value of $kw to 2 in the code, use the following commands at the DB<> prompt:

DB<1> $kw = 2
... nothing is printed here ...
DB<1> print $kw
2
DB<1> V main kw
$kw = '2'

In this example, the variable $kw is created and defined in the program environment. You cannot modify the source code in the original program, but you can add items to the name space.

In some cases, your program may have redirected its output to STDOUT and therefore whatever it is printing will not be shown on the console. To evaluate an expression and print its value out to the console regardless of how STDOUT is redirected, you can use the p command. The p command evaluates an expression in the current program's environment and prints it out to the debugger console. Basically, the print command prints the output to wherever STDOUT is redirected, whereas the p command is equivalent to the following print command:

print DB::OUT

The command above forces output from a print command to where the DB:: package prints its output.

Searching for Patterns

To look for certain strings in the source code, you can use the forward slash command followed by the string to look for. Note that there are no spaces between the / and the string you are looking for. The string can be specified between two slashes, but the second slash is optional. Actually, you can search for regular expressions, just as in Perl.

To search forward in the file, use the / operator. To search backward, use the question mark operator ( ? ).

The history of the commands you have executed is tracked in the debugger. Only commands greater than one character long are listed in this directory. To execute commands from the history list, use the bang operator ( ! ) followed by the index of the command. To execute a command from the history, type ! and the index of the command to redo. This should be familiar to Bash and C shell programmers.

To see the current history of commands in the buffer of commands in the debugger, type the H command. For example, in the middle of a debug session, if you type in the H command at the DB<3> prompt, you should expect to see three items listed in reverse order of execution:

DB<3> H
3: b 79
2: w 2
1: w 9
Subroutines

To list all the subroutines currently in the system, use the S command. The output from the S command lists all subroutines in any package that your code uses. For example, if you run the program in Listing 30.2 with the debugger, you will see output as shown in Figure 30.6.

Figure 30.6 : Listing subroutine names.


Listing 30.2. A sample listing.
1 #!/usr/bin/perl -d
2
3 use VRML;
4 use VRML::Cube;
5
6 my $header = VRML::new();
7 $header->VRML::startHeader;
8
9 $header->VRML::startSeparator;
10
11 my $cubeb = $header->VRML::putCube(
12 'width' => 0.5, 'height' => 0.5 , 'depth' => 0.5 ,
13 'translation' => [1,0,0]
14 );
15 my $cubed = $header->VRML::putCube(
16 'width' => 1, 'height' => 1 , 'depth' => 1 ,
17 'translation' => [1,1,0],
18 );
19 $header->VRML::stopSeparator;

At any time in a debug session, you can do a "stack trace," which is a listing of the calling order of the functions called so far. Be aware that if you are modifying the argument stack in any way, the values of the passed arguments might not be correct. The T command will do a stack trace for you.

Caveats

First of all, there is no way to restart the debugger if there is a problem. If you overstep something, you have to start all over. This means getting out of the program and restarting the debugger.

Second, the debugger itself is not completely debugged yet. If you notice certain problems, such as your commands not being recognized, it's probably because you typed too many characters at the prompt.

Table 30.1 lists the information about the available debugger commands. All information in this table is gleaned from the perl5db.pl source file. Keep this table handy so that you don't have to go to the file to see what options are available.

Table 30.1. The commands available from the debugger.
Command Description
a [ ln ] command Sets an action to take before the line is executed.
b Sets an unconditional breakpoint at the current line.
b [ ln ] [ cond ] Sets a breakpoint if the condition is true at the specified line number.
b sname [ cond ] Sets a breakpoint at the first line inside the subroutine sname() .
c Continues until the next breakpoint or until the end of the program.
c line Continues and stops at the specified line.
d [ line ] Deletes the breakpoint at a given line.
D Deletes all breakpoints.
f filename Switches to the filename as the default.
H - number Displays history of all commands longer than one character.
L Lists all breakpoints and actions.
l min+incr Lists incr+1 lines starting at line #min .
l min-max Lists lines from min to max , inclusively.
l line Lists one line of code at a specified line.
l Lists the next 10 lines of code from the last location.
l name Lists a subroutine by name.
n Next code at the same level. Steps over subroutine calls.
p expr Same as print DB::OUT expr in current package.
q or ^D Quits. You cannot use quit .
r Returns from current subroutine.
s Single-step over code. Steps into subroutines.
S Lists all known subroutine names in the current scope.
t Toggles trace mode on and off.
T Performs a stack trace.
V Lists all variables in all used packages.
V pkg List all variables in a given package.
V pkg var Lists all variables in a package that have var in them.
w line Lists five lines before and five lines after current line.
<CR> Repeats last n or s .
- Lists the previous window.
/ regexp / Searches forward for a pattern using a regular expression.
? regexp ? Searches backward for a pattern using a regular expression.
< command Defines the command before the prompt.
> command Defines the command after the prompt.
! number Redoes a command (the default is the previous command).
! - number Redoes number\'th to the last command.
= [ alias value ] Starts a command alias.
= Lists all the current aliases.
command Executes as a Perl statement in the current package.
Customizing Your Debugger Environment

There are ways to customize your debugger environment. If you do not like the one-character commands that come with the debugger, you can use different aliases. There is a hash in the DB:: package called %alias() that contains the command strings. You can substitute your own commands in place of the existing ones using the = command. Since most of the time you'll want to keep your changes consistent between debug sessions, you can edit a file called .perldb in the current working directory and place the assignments there. Here's a sample .perldb file:

$DB::alias{'ln'} = 's/ln/p $1/';
$DB::alias{'z'} = 's/z/l/';

These two lines will substitute the value of p for every command ln you type, and the value of l for every z command. Of course, you'll probably want to alias long commands into short one-character sequences to save yourself some time.

Using the debugger should not be your only method for getting bugs out of the system. The -w switch is important if you want Perl to do checking and warn you of error conditions while executing. The types of messages generated vary from warnings to notifications of fatal errors that can cause the program to abort.

For More Information

Reading the source file perl5db.pl gives you a few clues about how the debugger works and the commands that are available during a debug session. Consult the perldebug.html page at www.metronet.com . This file contains the full list of all the options in the debug environment. Review the perldiag.html page for a list of possible diagnostic values you get from using the w switch.

Summary

Nothing really beats the use of well-placed print statements to do debugging. However, Perl does offer a simple yet powerful debugging tool with the -d option. The interactive debugger lets you step through code, into or over subroutines, set breakpoints, execute commands, and look at variables in a Perl program.

[Dec 19, 2017] Antibugging in Perl 7 Tips for Reducing Complexity

Notable quotes:
"... The complexity of a program is a function of several factors: ..."
Dec 19, 2017 | www.informit.com

"Complexity is the enemy, and our aim is to kill it." -Jan Baan

One of Perl's greatest strengths is its expressiveness and extreme conciseness. Complexity is the bane of software development: when a program grows beyond a certain size, it becomes much harder to test, maintain, read, or extend. Unfortunately, today's problems mean this is true for every program we need. Anything you can do to minimize the complexity of your program will pay handsome dividends.

The complexity of a program is a function of several factors:

Whenever a language allows you to change some code to reduce any of these factors, you reduce complexity.

3.7.1 Lose the Temporary Variables

The poster child for complexity is the temporary variable. Any time a language intrudes between you and the solution you visualize, it diminishes your ability to implement the solution. All languages do this to some degree; Perl less than most. 13 In most languages, you swap two variables a and b with the following algorithm:

Declare temp to be of the same type as a and b
temp = a;
a = b;
b = temp;

But most languages are not Perl:

($b, $a) = ($a, $b);

Iterating over an array usually requires an index variable and a count of how many things are currently stored in the array:

int i;
for (i = 0; i < count_lines; i++) 
 {
 strcat (line[i], suffix);
 }

Whereas in Perl, you have the foreach construct borrowed from the shell:

foreach my $line (@lines) { $line .= $suffix }

And if you feel put out by having to type foreach instead of just for , you're in luck, because they're synonyms for each other; so just type for if you want (Perl can tell which one you mean).

Because functions can return lists, you no longer need to build special structures just to return multivalued data. Because Perl does reference-counting garbage collection, you can return variables from the subroutine in which they are created and know that they won't be trampled on, yet their storage will be released later when they're no longer in use. And because Perl doesn't have strong typing of scalars, you can fill a hierarchical data structure with heterogeneous values without having to construct a union datatype and some kind of type descriptor.

Because built-in functions take lists of arguments where it makes sense to do that, you can pass them the results of other functions without having to construct an iterative loop:

unlink grep /~$/, readdir DIR;

And the map function lets you form a new list from an old one with no unnecessary temporary variables:

open PASSWD, '/etc/passwd' or die "passwd: $!\n";
my @usernames = map /^([^:]+)/, <PASSWD>;
close PASSWD;

Because Perl's arrays grow and shrink automatically and there are simple operators for inserting, modifying, or deleting array elements, you don't need to build linked lists and worry if you've got the traversal termination conditions right. And because Perl has the hash data type, you can quickly locate a particular chunk of information by key or find out whether a member of a set exists.

3.7.2 Scope Out the Problem

Of course, sometimes temporary variables are unavoidable. Whenever you create one though, be sure and do it in the innermost scope possible (in other words, within the most deeply nested set of braces containing all references to the variable).

Create variables in the innermost scope possible.

For example, let's say somewhere in my program I am traversing my Netscape history file and want to save the URLs visited in the last 10 days in @URLs :

use Netscape::History;
my $history = new Netscape::History;
my (@URLs, $url);
while (defined($url = $history->next_url() )) 
 {
 push @URLs, $url if 
    time - $url->last_visit_time < 10 * 24 * 3600;
 }

This looks quite reasonable on the face of it, but what if later on in our program we create a variable called $history or $url ? We'd get the message

"my" variable $url masks earlier declaration in same scope

which would cause us to search backward in the code to find exactly which one it's referring to. Note the clause " in same scope " -- if in the meantime you created a variable $url at a different scope, well, that may be the one you find when searching backward with a text editor, but it won't be the right one. You may have to check your indentation level to see the scope level.

This process could be time-consuming. And really, the problem is in the earlier code, which created the variables $history or $url with far too wide a scope to begin with. We can (as of perl 5.004) put the my declaration of $url right where it is first used in the while statement and thereby limit its scope to the while block. As for $history , we can wrap a bare block around all the code to limit the scope of those variables:

use Netscape::History;
my @URLs;
 {
 my $history = new Netscape::History;
 while (defined(my $url = $history->next_url() )) 
  {
  push @URLs, $url 
   if time - $url->last_visit_time < 10 * 24 * 3600;
  }
 }

If you want to create a constant value to use in several places, use constant.pm to make sure it can't be overwritten:

$PI = 3.1415926535897932384;

use constant PI => 3.1415926535897932384;

my $volume = 4/3 * PI * $radius ** 3;

$PI = 3.0; # The 'Indiana maneuver' works!
PI = 3.0; # But this does not

In response to the last statement, Perl returns the error message, " Can't modify constant item in scalar assignment ."

constant.pm creates a subroutine of that name which returns the value you've assigned to it, so trying to overwrite it is like trying to assign a value to a subroutine call. Although the absurdity of that may sound like sufficient explanation for how use constant works, in fact, the latest version of perl allows you to assign a value to a subroutine call, provided the result of the subroutine is a place where you could store the value. For example, the subroutine could return a scalar variable. The term for this feature is lvaluable subroutine . But since the results of the subroutines created by use constant aren't lvalues, lvaluable subroutines won't cause problems for them.

[Dec 19, 2017] Cultured Perl: Debugging Perl with ease. Catch the bugs before they bite

Nov 01, 2000 | www.ibm.com

Bugs are as inevitable as death and taxes. Nevertheless, the following material should help you avoid the pitfalls of bugs.

... ... ...

First let's simply make sure the bug is repeatable. We'll set an action on line 8 to print $line where the error occurred, and run the program.

perl -d ./buggy.pl buggy.pl

use Data::Dumpe

a 8 print 'The line variable is now ', Dumper $line

The Data::Dumper module loads so that the autoaction can use a nice output format. The autoaction is set to do a print statement every time line 8 is reached. Now let's watch the show.

[Dec 08, 2017] Perl Debugger Tutorial 10 Easy Steps to Debug Perl Program

Dec 08, 2017 | www.thegeekstuff.com

Perl Debugger Tutorial: 10 Easy Steps to Debug Perl Program by Balakrishnan Mariyappan on May 19, 2010

https://apis.google.com/se/0/_/+1/fastbutton?usegapi=1&size=medium&origin=http%3A%2F%2Fwww.thegeekstuff.com&url=http%3A%2F%2Fwww.thegeekstuff.com%2F2010%2F05%2Fperl-debugger%2F&gsrc=3p&jsh=m%3B%2F_%2Fscs%2Fapps-static%2F_%2Fjs%2Fk%3Doz.gapi.en_US.7iE0RPXkeyg.O%2Fm%3D__features__%2Fam%3DAQ%2Frt%3Dj%2Fd%3D1%2Frs%3DAGLTcCPtrDcrcZ6TwfUke349lDWwAOzBUw#_methods=onPlusOne%2C_ready%2C_close%2C_open%2C_resizeMe%2C_renderstart%2Concircled%2Cdrefresh%2Cerefresh&id=I0_1512705132381&_gfid=I0_1512705132381&parent=http%3A%2F%2Fwww.thegeekstuff.com&pfname=&rpctoken=25025448

http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.thegeekstuff.com%2F2010%2F05%2Fperl-debugger%2F&send=false&layout=button_count&width=450&show_faces=false&action=like&colorscheme=light&font&height=21

http://platform.twitter.com/widgets/tweet_button.6b8337773e8a8ecc4f0b054fec8f1482.en.html#dnt=false&id=twitter-widget-0&lang=en&original_referer=http%3A%2F%2Fwww.thegeekstuff.com%2F2010%2F05%2Fperl-debugger%2F&size=m&text=Perl%20Debugger%20Tutorial%3A%2010%20Easy%20Steps%20to%20Debug%20Perl%20Program&time=1512705132548&type=share&url=http%3A%2F%2Fwww.thegeekstuff.com%2F2010%2F05%2Fperl-debugger%2F

Earlier we discussed the basics of how to write and execute a perl program using Perl Hello World Example .

In this article, Let us review how to debug a perl program / script using Perl debugger , which is similar to the gdb tool for debugging C code .

To debug a perl program, invoke the perl debugger using "perl -d" as shown below.

# perl -d  ./perl_debugger.pl

To understand the perl debugger commands in detail, let us create the following sample perl program (perl_debugger.pl).

$ cat perl_debugger.pl
#!/usr/bin/perl -w

# Script to list out the filenames (in the pwd) that contains specific pattern.

#Enabling slurp mode
$/=undef;

# Function : get_pattern
# Description : to get the pattern to be matched in files.
sub get_pattern
{
my $pattern;
print "Enter search string: ";
chomp ($pattern = <> );
return $pattern;
}

# Function : find_files
# Description : to get list of filenames that contains the input pattern.
sub find_files
{
my $pattern = shift;
my (@files,@list,$file);

# using glob, obtaining the filenames,
@files = <./*>;

# taking out the filenames that contains pattern.
@list = grep {
$file = $_;
open $FH,"$file";
@lines = <$FH>;
$count = grep { /$pattern/ } @lines;
$file if($count);
} @files;
return @list;
}
# to obtain the pattern from STDIN
$pattern = get_pattern();

# to find-out the list of filenames which has the input pattern.
@list = find_files($pattern);

print join "\n",@list;
1. Enter Perl Debugger

# perl -d ./perl_debugger.pl

it prompts,
DB<1>

2. View specific lines or subroutine statements using (l)

DB<1> l 10
10: my $pattern;

DB<2> l get_pattern
11 {
12: my $pattern;
13: print "Enter search string: ";
14: chomp ($pattern = );
15: return $pattern;
16 }

3. Set the breakpoint on get_pattern function using (b)

DB<3> b find_files

4. Set the breakpoint on specific line using (b)

DB<4> b 44

5. View the breakpoints using (L)

DB<5> L
./perl_debugger.pl:
22: my $pattern = shift;
break if (1)
44: print join "\n",@list;
break if (1)

6. step by step execution using (s and n)

DB<5> s
main::(./perl_debugger.pl:39): $pattern = get_pattern();

DB<5> s
main::get_pattern(./perl_debugger.pl:12):
12: my $pattern;

Option s and n does step by step execution of each statements. Option s steps into the subroutine. Option n executes the subroutine in a single step (stepping over it).

The s option does stepping into the subroutine but while n option which would execute the subroutine(stepping over it).

7. Continue till next breakpoint (or line number, or subroutine) using (c)

DB<5> c
Enter search string: perl
main::find_files(./perl_debugger.pl:22):
22: my $pattern = shift;

8. Continue down to the specific line number using (c)

DB<5> c 36
main::find_files(./perl_debugger.pl:36):
36: return @list;

9. Print the value in the specific variable using (p)

DB<6> p $pattern
perl

DB<7> c
main::(./perl_debugger.pl:44): print join "\n",@list;
DB<7> c
./perl_debugger.pl
Debugged program terminated. Use q to quit or R to restart,
use o inhibit_exit to avoid stopping after program termination,
h q, h R or h o to get additional info.

After the last continue operation, the output gets printed on the stdout as "./perl_debugger.pl" since it matches the pattern "perl".

10. Get debug commands from the file (source)

Perl debugger can get the debug command from the file and execute it. For example, create the file called "debug_cmds" with the perl debug commands as,

c
p $pattern
q

Note that R is used to restart the operation(no need quit and start debugger again).
DB<7> R
DB<7> source debug_cmds
>> c
Enter search string: perl
./perl_debugger.pl
Debugged program terminated. Use q to quit or R to restart,
use o inhibit_exit to avoid stopping after program termination,
h q, h R or h o to get additional info.
>> p $pattern
perl
>> q

Note : If you are relatively new to perl, refer to our previous article: 20 perl programming tips for beginners .

Summary of perl debugger commands

Following options can be used once you enter the perl debugger.

[Dec 03, 2017] Debugging Regular Expressions

Dec 03, 2017 | my.safaribooksonline.com

Not for the fainthearted, if you want to see how a regular expression runs when used in a match or substitution, use the core re pragma with its debug option:

% perl -Mstrict -Mwarnings
use re qw(debug);
$_ = "cats=purr, dog=bark";
my %sound = /(\w+)=(\w+)/g;
^D
Compiling REx `(\w+)=(\w+)'
size 15 first at 4
1: OPEN1(3)
3: PLUS(5)
4: ALNUM(0)
5: CLOSE1(7)
7: EXACT <=>(9)
9: OPEN2(11)
11: PLUS(13)
12: ALNUM(0)
13: CLOSE2(15)
15: END(0)
floating `=' at 1..2147483647 (checking floating) stclass `ALNUM' plus
minlen 3
Guessing start of match, REx `(\w+)=(\w+)' against `cats=purr,
dog=bark'...
Found floating substr `=' at offset 4...
Does not contradict STCLASS...
Guessed: match at offset 0
Matching REx `(\w+)=(\w+)' against `cats=purr, dog=bark'
Setting an EVAL scope, savestack=3
0 <> <cats=purr, d> | 1: OPEN1
0 <> <cats=purr, d> | 3: PLUS
ALNUM can match 4 times out of 32767...
Setting an EVAL scope, savestack=3
4 <cats> <=purr, d> | 5: CLOSE1
4 <cats> <=purr, d> | 7: EXACT <=>
5 <cats=> <purr, d> | 9: OPEN2
5 <cats=> <purr, d> | 11: PLUS

Setting an EVAL scope, savestack=3
9 <=purr> <, dog=b> | 13: CLOSE2
9 <=purr> <, dog=b> | 15: END
Match successful!
Guessing start of match, REx `(\w+)=(\w+)' against `, dog=bark'...
Found floating substr `=' at offset 5...
By STCLASS: moving 0 --> 2
Guessed: match at offset 2
Matching REx `(\w+)=(\w+)' against `dog=bark'
Setting an EVAL scope, savestack=3
11 <urr, > <dog=bar> | 1: OPEN1
11 <urr, > <dog=bar> | 3: PLUS
ALNUM can match 3 times out of 32767...
Setting an EVAL scope, savestack=3
14 <rr, dog> <=bark> | 5: CLOSE1
14 <rr, dog> <=bark> | 7: EXACT <=>
15 <rr, dog=> <bark> | 9: OPEN2
15 <rr, dog=> <bark> | 11: PLUS
ALNUM can match 4 times out of 32767...
Setting an EVAL scope, savestack=3
19 <rr, dog=bark> <> | 13: CLOSE2
19 <rr, dog=bark> <> | 15: END
Match successful!
Freeing REx: `(\w+)=(\w+)'

debugcolor option instead of debug , you'll get some form of highlighting or coloring in the output that'll make it prettier, if not more understandable

[Dec 01, 2017] regex - Debugging Perl Regular expression

Dec 01, 2017 | stackoverflow.com

down vote favorite 1

AnonGeek ,Jun 20, 2012 at 20:37

I am trying to debug few regular expressions using:
perl -Mre=debug file.pl

The file.pl script has many regular expression. Some of them are repeated. Using above syntax, all the regex in file.pl are being debugged.

Is there a way to tell Perl to debug only a particular regex in a script?

I am familiar with YAPE::Regex module, but that is not what I require. So please don't suggest to use that.

Ehtesh Choudhury ,Jun 20, 2012 at 20:45

Why not just comment out the other regexes, or run just the particular regex on the command line, via perl -e ? – Ehtesh Choudhury Jun 20 '12 at 20:45

AnonGeek ,Jun 20, 2012 at 20:55

the script is very compilcated(12000 LOC). If I will comment out any of regex then the execution will fail..Also if I provide dummy values, then it will give unexpected results :( – AnonGeek Jun 20 '12 at 20:55

Oleg V. Volkov ,Jun 20, 2012 at 20:41

As with many other pragmas, you can use no to cancel previous use .
use re 'debug';

$str=~/\d{3}/;

no re 'debug';

$str=~/\d{3}/;

Denis Ibaev ,Jun 20, 2012 at 20:48

As of 5.9.5 the directive use re 'debug' and its equivalents are lexically scoped, as the other directives are.

Use:

{
    use re 'debug';
    # Debugged regexp here.
}

AnonGeek ,Jun 20, 2012 at 21:10

Is this also supported in 5.8.8? I am putting it under a condition but it is enabling it globally for all regex. – AnonGeek Jun 20 '12 at 21:10

Denis Ibaev ,Jun 21, 2012 at 5:24

No, since version 5.9.5. In 5.8.8 you need use no statement. – Denis Ibaev Jun 21 '12 at 5:24

[Nov 30, 2017] debugging - Perl Debugger Filehandle as Input

Highly recommended!
Nov 30, 2017 | stackoverflow.com
I have this problem: I need to control the perl-debugger from an external script. By research I found out about various solutions, but I don't understand them. I failed to properly set up the RemotePort option (editing ".perldb"), which was the first I tried, and found no useful information on providing a filehandle from which the debugger would get its input (by somehow setting @cmdfhs) I found both options over here: http://search.cpan.org/~nwclark/perl-5.8.6/lib/perl5db.pl

It would be nice if you could tell me how to provide the filehandle from which the debugger gets its input, or if you know a link where this is explained?

Casper ,Jun 28, 2015 at 21:53

Here's a simple example setting it up using RemotePort , which seemed easier to me:

The trick to using RemotePort is that you have to have someone listening on the remote end BEFORE you launch the script to be debugged.

As soon as you launch your script with -d Perl will attempt to connect to RemotePort . So you have to make sure the initial connection succeeds by having someone listening there beforehand.

Here I assume some Linux/Unix variant, which has the netcat utility installed. We use netcat to wait for incoming connections in this example, but you can use anything else you wish too which is able to create a service port and shuffle data between that and the current TTY:

In terminal 1

 # Use netcat to listen for incoming connections on port 9999
 > nc -l -p 9999

In terminal 2

 # Start perl with -d and request a RemotePort connection 
 > PERLDB_OPTS=RemotePort=127.0.0.1:9999 perl -d my_script.pl

As soon as you do that in terminal 1 you will see something like this:

Loading DB routines from perl5db.pl version 1.39_10
Editor support available.

Enter h or 'h h' for help, or 'man perldebug' for more help.

main::(my_script.pl:4):
  DB<1>

There you go..debug away.

Devel::Trepan is a gdb-like debugger. Although it has remote control, you can also run it at the outset with the option --command which will "source" (in the gdb-sense) or run a series of debugger commands.

To go into remote control, either start the debugger using the --server option or inside the debugger use the " server " command once inside the debugger.

See Options for a list of options you can give at the outset.

[Nov 18, 2017] Using the built-in debugger of Perl as REPL by Gabor Szabo

Youtube video, Mainly explain how to use x command in Perl debugger.
Nov 18, 2017 | www.youtube.com

The command line debugger that comes with perl is very powerful.
Not only does it allow us to debug script but it can be used as a REPL - a Read Eval Print Loop to explore the capabilities of the language. There are a few basic examples in this screencast.

http://perlmaven.com/using-the-built-...

To see all the Perl tutorials visit http://perlmaven.com/perl-tutorial

About Perl Programming and Perl programmers.

In this screencast:

perl -d e 1

p - print scalar
x - print data structure
b subname - set breakpoint

[Nov 17, 2017] Using the built-in debugger of Perl by Gabor Szabo

Youtube video, 9 min.
Nov 17, 2017 | www.youtube.com

Perl comes with a very powerful built-in command line debugger. In this screencast you can see basics how to use it.

For blog entries and for more screencasts see http://perlmaven.com/

About Perl Programming and Perl programmers.

For the blog entry of this screencast visit
http://perlmaven.com/using-the-built-...

Debugger commands used:

q - quit,
h - help,
p - print,
s - step in,
n - step over,
r - step out,
T - stack trace
l - listing code

The Padre project can be found here: http://padre.perlide.org/

The book mentioned was Pro Perl Debugging: http://www.apress.com/9781590594544

If you are interested an on-site Perl training contact me http://szabgab.com/contact.html

[Nov 15, 2017] Basic Debugger Commands

Notable quotes:
"... pseudo-signal handlers, ..."
"... programmatic debugger control ..."
Nov 15, 2017 | my.safaribooksonline.com

Debugging is just an extreme case of dynamic analysis. Third-party code can be extremely convoluted (so can your own code, of course, but you don't usually think of it that way because you're familiar with it; you knew it when it was just a subroutine); sometimes you just can't tell how part of the code fits in, or whether it's called at all. The code is laid out in some arrangement that makes no sense; if only you could see where the program would actually go when it was run.

Well, you can, using Perl's built-in debugger. Even though you're not actually trying to find a bug, the code-tracing ability of the debugger is perfect for the job.

This isn't the place for a full treatment of the debugger (you can see more detail in [ SCOTT01 ]), but fortunately you don't need a full treatment; a subset of the commands is enough for what you need to do. (Using the debugger is like getting in a fight; it's usually over very quickly without using many of the fancy moves you trained for.)

-d command-line flag; either edit the program to add -d to the shebang line, or run the program by invoking Perl explicitly:

% perl -d program argument argument...

Make sure that the perl in your path is the same one in the shebang line of program or you'll go crazy if there are differences between the two perls.

Basic Debugger Commands

Armed with these commands, we can go code spelunking. Suppose you are debugging a program containing the following code fragment:

77 for my $url (@url_queue)
78 {
79 my $res = $ua->request($url);
80 summarize($res->content);
81 }

and you know that whenever the program gets to the URL http://www.perlmedic.com/fnord.html something strange happens in the summarize() subroutine. You'd like to check the HTTP::Response object to see if there were any redirects you didn't know about. You start the program under the debugger and type:

DB<1> b 80 $url =~ /fnord/
DB<2>

The program will run until it has fetched the URL you're interested in, at which point you can examine the response object -- here's an example of what it might look like:

Perl 5.8.0 and later will give you a stack trace anyway if you run a program under the debugger and some code triggers a warning. But suppose you are either running under an earlier perl, or you'd really like to have a debugger prompt at the point the warning was about to happen.

You can combine two advanced features of Perl to do this: pseudo-signal handlers, and programmatic debugger control .

A signal handler is a subroutine you can tell Perl to execute whenever your program receives a signal. For instance, when the user interrupts your program by pressing Control-C, that works by sending an INT signal to your program, which interprets it by default as an instruction to stop executing.

There are two pseudo-signals, called __WARN__ and __DIE__ . They aren't real signals, but Perl "generates" them whenever it's told to issue a warning or to die, respectively. You can supply code to be run in those events by inserting a subroutine reference in the %SIG hash (see perlvar ) as follows:

$SIG{__WARN__} = sub { print "Ouch, I'm bad" };

(Try it on some code that generates a warning.)

The next piece of the solution is that the debugger can be controlled from within your program; the variable $single in the special package DB determines what Perl does at each statement: 0 means keep going, and 1 or 2 mean give a user prompt. 1 So setting $DB::single to 1 in a pseudo-signal handler will give us a debugger prompt at just the point we wanted.

1 . The difference between the two values is that a 1 causes the debugger to act as though the last n or s command the user typed was s , whereas a 2 is equivalent to an n . When you type an empty command in the debugger (just hit Return), it repeats whatever the last n or s command was.

Putting the pieces together, you can start running the program under the debugger and give the commands:

DB<1> $SIG{__WARN__} = sub { warn @_; $DB::single = 1 }
DB<2>

Now the program will breakpoint where it was about to issue a warning, and you can issue a T command to see a stack trace, examine data, or do anything else you want. 2 The warning is still printed first.

2 . Under some circumstances, the breakpoint might not occur at the actual place of warning: The current routine might return if the statement triggering the warning is the last one being executed in that routine.

Unfortunately, no __DIE__ pseudo-signal handler will return control to the debugger (evidently death is considered too pressing an engagement to be interrupted). However, you can get a stack trace by calling the confess() function in the Carp module:

DB<1> use Carp
DB<2> $SIG{__DIE__} = sub { confess (@_) }

The output will look something like this:

DB<3>
Insufficient privilege to launch preemptive strike at wargames line
109.
main::__ANON__[(eval 17)[/usr/lib/perl5/5.6.1/
perl5db.pl:1521]:2]('Insufficient privilege to launch preemptive
strike at wargames line 109.^J') called at wargames line 121
main::preemptive('Strike=HASH(0x82069d4)') called at wargames
line 109
main::make_strike('ICBM=HASH(0x820692c)') called at wargames
line 74
main::icbm('Silo_ND') called at wargames line 32
main::wmd('ICBM') called at wargames line 22
main::strike() called at wargames line 11
main::menu() called at wargames line 5
Debugged program terminated. Use q to quit or R to restart,
use O inhibit_exit to avoid stopping after program termination,
h q, h R or h O to get additional info.

I've often found it amusing that the debugger refers to the program at this point as "debugged."

[Nov 14, 2017] Perl archeology Need help in refactoring of old Perl code that does not use strict

Nov 14, 2017 | perlmonks.com

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

This is kind of topic that previously was reserved to Cobol and PL/1 forums ;-) but now Perl is almost 30 years old and it looks like the space for Perl archeology is gradually opening ;-).

I got a dozen of fairly large scripts (several thousand lines each) written in a (very) early version of Perl 5 (below Perl 5.6), I now need:

1. Convert them to use strict pragma. The problem is that all of them share (some heavily, some not) information from main program to subroutines (and sometimes among subroutines too) via global variables in addition to (or sometimes instead of) parameters. Those scripts mostly do not use my declarations either.

So I need to map variables into local and global namespaces for each subroutine (around 40 per script; each pretty small -- less then hundred lines) to declare them properly.

As initial step I just plan use global variable with namespace qualification or our lists for each subroutine. Currently I plan to postprocess output of perl -MO=Xref old_perl_script.pl

and generate such statement. Is there a better way ?

2. If possible, I want to split the main namespace into at least two chunks putting all subroutines into another namespace, or module. I actually do not know how to export subroutines names into other namespace (for example main::) when just package statements is used in Perl as in example below. Modules do some magic via exporter that I just use but do not fully understand. For example if we have

#main_script ... ... ... x:a(1,2,3); ... ... ... package x; sub a {...) sub b {...} sub c {...} package y; ... ... ... [download] How can I access subs a,b,c without qualifying them with namespace x from the main:: namespace?

3. Generally this task looks like a case of refactoring. I wonder, if any Perl IDE has some of required capabilities, or are there tools that can helpful.

My time to make the conversion is limited and using some off the shelf tools that speed up the process would be a great help.

Any advice will be greatly appreciated.

AnomalousMonk (Chancellor) on Nov 14, 2017 at 07:20 UTC

Re: Perl archeology: Need help in refactoring of old Perl code that does not use strict

I'd like to suggest that you also need a

Step 0: Write a test suite that the current code passes for all normal modes of operation and for all failure modes.
With this test suite, you can be reasonably certain that refactored code isn't just going to be spreading the devastation.

Given that you seem to be describing a spaghetti-coded application with communication from function to function via all kinds of secret tunnels and spooky-action-at-a-distance global variables, I'd say you have a job on your hands just with Step 0. But you've already taken a test suite into consideration... Right?


Give a man a fish : <%-{-{-{-<

Monk::Thomas (Friar) on Nov 14, 2017 at 12:14 UTC

Re^2: Perl archeology: Need help in refactoring of old Perl code that does not use strict

by Monk::Thomas (Friar) on Nov 14, 2017 at 12:14 UTC

This is what I would do after 'Step 0':

If the variable does change during the run then pick a different function first. When you got the global state disentangled a bit it's a lot easier to reason about what this code is doing. Everything that's still using a global needs to be treated with very careful attention.

Corion (Pope) on Nov 14, 2017 at 08:45 UTC

Re: Perl archeology: Need help in refactoring of old Perl code that does not use strict

In addition to AnomalousMonk s advice of a test suite, I would suggest at the very least to invest the time up front to run automatic regression tests between whatever development version of the program you have and the current "good" (but ugly) version. That way you can easily verify whether your change affected the output and operation of the program. Ideally, the output of your new program and the old program should remain identical while you are cleaning things up.

Note that you can enable strict locally in blocks, so you don't need to make the main program compliant but can start out with subroutines or files and slowly convert them.

For your second question, have a look at Exporter . Basically it allows you to im/export subroutine names between packages:

package x;
use Exporter 'import';
our @EXPORT_OK = ('a', 'b', 'c');
[download] #main_script use x 'a', 'b'; # makes a() and b() available in the main namespace [download]

To find and collect the global variables, maybe it helps you to dump the global namespace before and after your program has run. All these names are good candidates for being at least declared via our to make them visible, and then ideally removed to pass the parameters explicitly instead of implicitly:

#!perl -w
use strict;

our $already_fixed = 1; # this won't show up

# Put this right before the "uncleaned" part of the script starts
my %initial_variables;
BEGIN {
    %initial_variables = %main::; # make a copy at the start of the program
}
END {
#use Data::Dumper;
#warn Dumper \%initial_variables;
#warn Dumper \%main::;
    # At the end, look what names came newly into being, and tell us about them:
    for my $key (sort keys %main::) {
        if( ! exists $initial_variables{ $key } ) {
            print "Undeclared global variable '$key' found\n";
            
            my $glob = $main::{ $key };
            
            if( defined *{ $glob }{GLOB}) {
                print "used as filehandle *'$key', replace by a lexical filehandle\n";
            };
            if( defined *{ $glob }{CODE}) {
                print "used as subroutine '$key'\n"; # so maybe a false alarm unless you dynamically load code?!
            };
            if( defined *{ $glob }{SCALAR}) {
                print "used as scalar \$'$key', declare as 'our'\n";
            };
            if( defined *{ $glob }{ARRAY}) {
                print "used as array \@'$key', declare as 'our'\n";
            };
            if( defined *{ $glob }{HASH}) {
                print "used as hash \%'$key', declare as 'our'\n";
            };
        };
    };
}
no strict;

$foo = 1;
@bar = (qw(baz bat man));
open LOG, '<', *STDIN;
sub foo_2 {}
 
[download]

The above code is a rough cut and for some reason it claims all global names as scalars in addition to their real use, but it should give you a start at generating a list of undeclared names.

Also see Of Symbol Tables and Globs .

Anonymous Monk on Nov 14, 2017 at 08:26 UTC

Re: Perl archeology: Need help in refactoring of old Perl code that does not use strict (hurry up and wait)

1) ... strict pragma ...My time to make the conversion is limited and using some off the shelf tools that speed up the process would be a great help.

Hurry up and leave it alone :)

use strict; itself confers no benefits; The benefits come from avoidance of the bad practices forbidden by strict :)

That pretty much means convert one at a time by hand after you have learned the understanding of importance of knowing :) Speed kills

2. If possible ... I do not understand ...

That is a hint you shouldn't be refactoring anything programmatically. There are a million nodes on perlmonks, and a readers digest version might be Modern Perl a loose description of how experienced and effective Perl 5 programmers work....You can learn this too.

Hurry up and bone up

3. Generally this task looks like a case of refactoring. I wonder, if any Perl IDE has some of required capabilities, or are there tools that can helpful.

I hope you have foot insurance :) happy hunting :) perlcritic , PPI / PPIx::XPath , PPIx::EditorTools ,
App::EditorTools - Command line tool for Perl code refactoring
Code::CutNPaste - Find Duplicate Perl Code

So enjoy, test first, step0++

[Nov 13, 2017] perl - Why use strict and warnings

Nov 13, 2017 | stackoverflow.com

down vote favorite 12

TLP , Nov 5, 2011 at 23:04

It seems to me that many of the questions in the Perl tag could be solved if people would use:
use strict;
use warnings;

I think some people consider these to be akin to training wheels, or unnecessary complications, which is clearly not true, since even very skilled Perl programmers use them.

It seems as though most people who are proficient in Perl always use these two pragmas, whereas those who would benefit most from using them seldom do. So, I thought it would be a good idea to have a question to link to when encouraging people to use strict and warnings .

So, why should a Perl developer use strict and warnings ?

Paul Tyng , Nov 5, 2011 at 23:08

I always wonder for stuff like this why they don't just make it the default and have the dev actually have to actively loosen stuff, where is the use loose;Paul Tyng Nov 5 '11 at 23:08

Daniel Böhmer , Nov 5, 2011 at 23:15

Like many cool and useful things Perl started as a hack, as a tool for the guy who invents it. Later it became more popular and an increasing number of unskilled people started using it. This is when you start thinking something like use strict was a good idea but backwards compatibility has already become a real problem to you:-( – Daniel Böhmer Nov 5 '11 at 23:15

ikegami , Nov 6, 2011 at 0:04

@JB Nizet, @Paul T., Actually, use strict; is on by default when you request the Perl 5.12 (or higher) language. Try perl -e"use v5.012; $x=123;" . no strict; actually turns it off. – ikegami Nov 6 '11 at 0:04

Joel Berger , Nov 6, 2011 at 3:05

Though in the end your point is true, the more times we say it, maybe the more people will hear. There has been some rumbling lately of trying to make more/better/modern Perl tutorials available and certainly strict/warnings will be on the top of each of these. For mine I plan to have s/w on the top of every snippet, just so that all newbies see it every time – Joel Berger Nov 6 '11 at 3:05

TLP , Nov 6, 2011 at 5:04

@JoelBerger No, actually it is nothing like it. Just like I said, it only has similar words in the title. It's for backwards compatibility. is the first sentence in the accepted answer, how do you propose that applies to my question? – TLP Nov 6 '11 at 5:04

ikegami , Nov 6, 2011 at 0:00

For starters, it helps find typos in variable names. Even experienced programmers make such errors. A common case is forgetting to rename an instance of a variable when cleaning up or refactoring code.

The pragmas catch many errors sooner than they would be caught otherwise, which makes it easier to find the root causes of the errors. The root cause might be the need for an error or validation check, and that can happen regardless or programmer skill.

What's good about Perl warnings is that they are rarely spurious, so there's next to no cost to using them.


Related reading: Why use my ?

ikegami , Nov 6, 2011 at 19:42

@TLP, I'm not about to make a study to quantify how much it helps. It should suffice to say that they help unconditionally. – ikegami Nov 6 '11 at 19:42

Jean , Sep 26, 2013 at 16:11

Why is it made optional then if it has so many benefits ? Why not enable it by default (like someone commented above) ? Is it for compatibility reasons ? – Jean Sep 26 '13 at 16:11

ikegami , Sep 26, 2013 at 16:34

@Jean, backwards compatibility. Note that use strict; is enabled by default if you use version 5.12 or newer of the language ( use 5.012; ). – ikegami Sep 26 '13 at 16:34

user2676847 , Aug 17, 2014 at 8:51

@Jean if you are writing a simple script you really don't want to get alerted by warnings about file handler names or for not declaring the variable before using them :-) – user2676847 Aug 17 '14 at 8:51

user966588

add a comment, Feb 12, 2013 at 8:31
Apparently use strict should(must) be used when you want to force perl to code properly which could be forcing declaration, being explicit on strings and subs i.e. barewords or using refs with caution. Note: if there are errors use strict will abort the execution if used.

While use warnings; will help you find typing mistakes in program like you missed a semicolon, you used 'elseif' and not 'elsif', you are using deprecated syntax or function, whatever like that. Note: use warnings will only provide warnings and continue execution i.e. wont abort the execution..

Anyway, It would be better if we go into details, which I am specifiying below

From perl.com (my favourite):

use strict 'vars';

which means that you must always declare variables before you use them.

If you don't declare you will probably get error message for the undeclared variable

Global symbol "$variablename" requires explicit package name at scriptname.pl line 3

This warning mean Perl is not exactly clear about what the scope of variable is. So you need to be explicit about your variables, which means either declaring them with my so they are restricted to the current block, or referring to them with their fully qualified name (for ex: $MAIN::variablename).

So, a compile-time error is triggered if you attempt to access a variable that hasn't met at least one of the following criteria:

use strict 'subs';

Consider two programs

# prog 1
   $a = test_value;
   print "First program: ", $a, "\n";
   sub test_value { return "test passed"; }
 Output: First program's result: test_value

# prog 2
   sub test_value { return "test passed"; }
   $a = test_value;
   print "Second program: ", $a, "\n";
 Output: Second program's result: test passed

In both cases we have a test_value() sub and we want to put its result into $a. And yet, when we run the two programs, we get two different results:

In the first program, at the point we get to $a = test_value; , Perl doesn't know of any test_value() sub, and test_value is interpreted as string 'test_value'. In the second program, the definition of test_value() comes before the $a = test_value; line. Perl thinks test_value as sub call.

The technical term for isolated words like test_value that might be subs and might be strings depending on context, by the way, is bareword . Perl's handling of barewords can be confusing, and it can cause bug in program.

The bug is what we encountered in our first program, Remember that Perl won't look forward to find test_value() , so since it hasn't already seen test_value(), it assumes that you want a string. So if you use strict subs; , it will cause this program to die with an error:

Bareword "test_value" not allowed while "strict subs" in use at ./a6-strictsubs.pl line 3.

Solution to this error would be
1. Use parentheses to make it clear you're calling a sub. If Perl sees $a = test_value();,
2. Declare your sub before you first use it

use strict;
sub test_value;  # Declares that there's a test_value() coming later ...
my $a = test_value;  # ...so Perl will know this line is okay.
.......
sub test_value { return "test_passed"; }

3. And If you mean to use it as a string, quote it.

So, This stricture makes Perl treat all barewords as syntax errors. *A bareword is any bare name or identifier that has no other interpretation forced by context. (Context is often forced by a nearby keyword or token, or by predeclaration of the word in question.)* So If you mean to use it as a string, quote it and If you mean to use it as a function call, predeclare it or use parentheses.

Barewords are dangerous because of this unpredictable behavior. use strict; (or use strict 'subs';) makes them predictable, because barewords that might cause strange behavior in the future will make your program die before they can wreak havoc

There's one place where it's OK to use barewords even when you've turned on strict subs: when you are assigning hash keys.

$hash{sample} = 6;   # Same as $hash{'sample'} = 6
%other_hash = ( pie => 'apple' );

Barewords in hash keys are always interpreted as strings, so there is no ambiguity.

use strict 'refs';

This generates a run-time error if you use symbolic references, intentionally or otherwise. A value that is not a hard reference is then treated as a symbolic reference . That is, the reference is interpreted as a string representing the name of a global variable.

use strict 'refs';

$ref = \$foo;       # Store "real" (hard) reference.
print $$ref;        # Dereferencing is ok.

$ref = "foo";       # Store name of global (package) variable.
print $$ref;        # WRONG, run-time error under strict refs.

use warnings;

This lexically scoped pragma permits flexible control over Perl's built-in warnings, both those emitted by the compiler as well as those from the run-time system.

From perldiag :

So The majority of warning messages from the classifications below i.e. W, D & S can be controlled using the warnings pragma.

(W) A warning (optional)
(D) A deprecation (enabled by default)
(S) A severe warning (enabled by default)

I have listed some of warnings messages those occurs often below by classifications. For detailed info on them and others messages refer perldiag

(W) A warning (optional):

Missing argument in %s
Missing argument to -%c
(Did you mean &%s instead?)
(Did you mean "local" instead of "our"?)
(Did you mean $ or @ instead of %?)
'%s' is not a code reference
length() used on %s
Misplaced _ in number

(D) A deprecation (enabled by default):

defined(@array) is deprecated
defined(%hash) is deprecated
Deprecated use of my() in false conditional
$# is no longer supported

(S) A severe warning (enabled by default)

elseif should be elsif
%s found where operator expected
(Missing operator before %s?)
(Missing semicolon on previous line?)
%s never introduced
Operator or semicolon missing before %s
Precedence problem: open %s should be open(%s)
Prototype mismatch: %s vs %s
Warning: Use of "%s" without parentheses is ambiguous
Can't open %s: %s

toolic , Nov 5, 2011 at 23:50

These two pragmas can automatically identify bugs in your code.

I always use this in my code:

use strict;
use warnings FATAL => 'all';

FATAL makes the code die on warnings, just like strict does.

For additional information, see: Get stricter with use warnings FATAL => 'all';

Also... The strictures, according to Seuss

tchrist , Nov 5, 2011 at 23:52

Actually, you have to delay the FATAL => "all" till runtime, by assigning to $SIG{__WARN__} = sub { croak "fatalized warning @_" }; or else you screw up the compiler trying to tell you what it needs to. – tchrist Nov 5 '11 at 23:52

toolic , Nov 6, 2011 at 0:06

@tchrist: This has always worked for me as-is and as documented. If you have found a case where it doesn't work as documented, please patch the documentation using perlbug . – toolic Nov 6 '11 at 0:06

moodywoody , Nov 5, 2011 at 23:21

There's a good thread on perlmonks about this question.

The basic reason obviously is that strict and warnings massively help you catch mistakes and aid debugging.

Rahul Reddy , Jul 1, 2013 at 7:35

Source :: Different blogs

Use will export functions and variable names to the main namespace by calling modules import() function.

A pragma is a module which influences some aspect of the compile time or run time behavior of perl.Pragmas give hints to the compiler.

Use warnings - perl complaints about variables used only once,improper conversions of strings into numbers,.Trying to write to files that are not opened .it happens at compile time.It is used to control warnings.

Use strict - declare variables scope. It is used to set some kind of discipline in the script.If barewords are used in the code they are interpreted.All the variables should be given scope ,like my,our or local.

MikasaAckerman , Jun 29, 2015 at 13:43

The "use strict" directive tells Perl to do extra checking during the compilation of your code. Using this directive will save you time debugging your Perl code because it finds common coding bugs that you might overlook otherwise.

dhana govindarajan , Jun 28, 2016 at 12:24

 use strict;use warnings;

strict and warnings are the mode for the perl program,and it is allowing the user to enter the code more liberally and more than that,that perl code will be look formal and its coding standard will be effective.

warnings means same like "-w" in the perl shabang line,so it will provide you the warnings generated by the perl program,it will display inthe terminal

Andreas Ährlund , Apr 6, 2015 at 14:58

Strict and warnings make sure your variables are not global.

It is much neater to be able to have variables unique for individual methods rather than having to keep track of each and every variable name.

$_, or no variable for certain functions, can also be useful to write more compact code quicker.

However, if you do not use strict and warnings, $_ becomes global!

[Nov 13, 2017] Basic debugging checklist by toolic

Feb 23, 2009 | perlmonks.com
checklist of tips and techniques to get you started.

This list is meant for debugging some of the most common Perl programming problems; it assumes no prior working experience with the Perl debugger ( perldebtut ). Think of it as a First Aid kit, rather than a fully-staffed state-of-the-art operating room.

These tips are meant to act as a guide to help you answer the following questions:

  1. Add the "stricture" pragmas ( Use strict and warnings ) use strict; use warnings; use diagnostics; [download]
  2. Display the contents of variables using print or warn warn "$var\n"; print "@things\n"; # array with spaces between elements [download]
  3. Check for unexpected whitespace
    • chomp , then print with delimiters of your choice, such as colons or balanced brackets, for visibility chomp $var; print ">>>$var<<<\n"; [download]
    • Check for unprintable characters by converting them into their ASCII hex codes using ord my $copy = $str; $copy =~ s/([^\x20-\x7E])/sprintf '\x{%02x}', ord $1/eg; print ":$copy:\n"; [download]
  4. Dump arrays, hashes and arbitrarily complex data structures. You can get started using the core module Data::Dumper . Should the output prove to be unsuitable to you, other alternatives can be downloaded from CPAN, such as Data::Dump , YAML , or JSON . See also How can I visualize my complex data structure? use Data::Dumper; print Dumper(\%hash); print Dumper($ref); [download]
  5. If you were expecting a ref erence, make sure it is the right kind (ARRAY, HASH, etc.) print ref $ref, "\n"; [download]
  6. Check to see if your code is what you thought it was: B::Deparse $ perl -MO=Deparse -p program.pl [download]
  7. Check the return ( error ) status of your commands
    • open with $! open my $fh, '<', 'foo.txt' or die "can not open foo.txt: $!"; [download]
    • system and backticks ( qx ) with $? if (system $cmd) { print "Error: $? for command $cmd" } else { print "Command $cmd is OK" } $out = `$cmd`; print $? if $?; [download]
    • eval with $@ eval { do_something() }; warn $@ if $@; [download]
  8. Use Carp to display variables with a stack trace of module names and function calls. use Carp qw(cluck); cluck("var is ($var)"); [download]

    Better yet, install and use the Carp::Always CPAN module to make your existing warn / die complain with a stack trace:

    $ perl -MCarp::Always program.pl [download]
  9. Demystify regular expressions by installing and using the CPAN module YAPE::Regex::Explain # what the heck does /^\s+$/ mean? use YAPE::Regex::Explain; print YAPE::Regex::Explain->new('/^\s+$/')->explain(); [download]
  10. Neaten up your code by installing and using the CPAN script perltidy . Poor indentation can often obscure problems.
  11. Checklist for debugging when using CPAN modules:
    • Check the Bug List by following the module's "View Bugs" link.
    • Is your installed version the latest version? If not, check the change log by following the "Changes" link. Also follow the "Other Tools" link to "Diff" and "Grep" the release.
    • If a module provides status methods, check them in your code as you would check return status of built-in functions: use WWW::Mechanize; if ($mech->success()) { ... } [download]
What's next? If you are not already doing so, use an editor that understands Perl syntax (such as vim or emacs), a GUI debugger (such as Devel::ptkdb ) or use a full-blown IDE. Lastly, use a version control system so that you can fearlessly make these temporary hacks to your code without trashing the real thing.

For more relevant discussions, refer to the initial Meditation post: RFC: Basic debugging checklist

Updated: Sep 8, 2009: Added CPAN Diff/Grep tip.
Updated: Jan 11, 2011: Added Carp::Always.

Bloodnok (Vicar) on Feb 23, 2009 at 01:19 UTC

Re: Basic debugging checklist

Damned decent posting :D ... just a couple of suggestions tho'...

Just a thought...

hexcoder (Chaplain) on Jun 21, 2014 at 11:07 UTC

Re: Basic debugging checklist

When debugging warnings from the perl core like Use of uninitialized value ... let the debugger pause right there. Then have a good look at the context that led to this situation and investigate variables and the callstack.

To let the debugger do this automatically I use a debugger customization script:

sub afterinit 
{
    $::SIG{'__WARN__'} = sub {
        my $warning = shift;
        if ( $warning =~ m{\s at \s \S+ \s line \s \d+ \. $}xms ) {
            $DB::single = 1;    # debugger stops here automatically
        }
        warn $warning;
    };
    print "sigwarn handler installed!\n";
    return;
}
[download]

Save the content to file .perldb (or perldb.ini on Windows) and place it in the current or in your HOME directory.

The subroutine will be called initially by the debugger and installs a signal handler for all warnings. If the format matches one from the perl core, execution in the debugger is paused by setting $DB::single = 1 .

LanX (Bishop) on Jun 21, 2014 at 12:30 UTC

Re^2: Basic debugging checklist

by LanX (Bishop) on Jun 21, 2014 at 12:30 UTC

hexcoder ++ :)

For further informations: afterinit , .perldb and other options are described in:

--> perldebug#Debugger Customization

Anonymous Monk on Oct 03, 2014 at 02:58 UTC

Re: Basic debugging checklist

perl -M re =debug foo.pl can help you see how perl interprets your regex, much in the way O=Deparse does for perl code

Anonymous Monk on Oct 31, 2014 at 07:38 UTC

Re^2: Basic debugging checklist

If you don't quite understand what you're looking at (output of deparse, perl syntax), then ppi_dumper can help you look at the right part of the manual, an example

$ ppi_dumper 2
PPI::Document
  PPI::Statement::Include
    PPI::Token::Word    'use'
    PPI::Token::Whitespace      ' '
    PPI::Token::Word    'constant'
    PPI::Token::Whitespace      ' '
    PPI::Token::Word    'X'
    PPI::Token::Whitespace      ' '
    PPI::Token::Operator        '=>'
    PPI::Token::Whitespace      ' '
    PPI::Token::Number          '1'
    PPI::Token::Operator        '/'
    PPI::Token::Number          '3'
    PPI::Token::Structure       ';'
  PPI::Token::Whitespace        '\n'
  PPI::Token::Whitespace        '\n'
[download]

So PPI::Token::Operator tells you "=>" is an operator

If you read perl /"perltoc" then you'll know that operators are documented in perlop

App::PPI::Dumper / ppi_dumper

wxPPIxregexplain.pl

[Nov 08, 2017] The Perl Debugger Starting

From the book Perl Debugged By: Peter Scott; Ed Wright (2001)
Nov 08, 2017 | www.amazon.com
7.2. Starting

The -d command line option makes your script run under the debugger. You can either add it to the options in the #! line at the beginning of your script, or you can override the options by explicitly running the script through perl. So for example, if wombat . pl currently has the -w option set, you can either change its first line to

#!/usr/bin/perl -wd

or you can type

% perl -wd wombat.pl
                                

to debug it without having to change the script. Unlike some debuggers, with this one you supply arguments to the program on the command line, not as part of a debugger command; for example:

% perl -wd wombat.pl kangaroo platypus wallaby
                                

The debugger will announce itself and provide a prompt:

Loading DB routines from perl5db.pl version 1.07
Emacs support available.

Enter h or `h h' for help.

main::(wombat.pl:1):   my $marsupial = shift;
  DB<1>

From now on we will elide everything before the first prompt (and the code on which it is stopped) when reproducing debugger sessions.

To begin, let's look at some simple commands. The very first of interest, of course, is h for help. The output from this is several screens long, which gives us an opportunity to mention an option we can apply to all commands: put a vertical bar ( | ) before any command and it will run the output through your pager (the program that prints things one screen at a time, waiting for you to tell it when to continue -- more or less more or less ).

7.2.1. Watch the Code Execute: s, n, r

Enter this simple program into debug . pl:

#!/usr/local/bin/perl -w
use strict;

my @parole = qw(Salutations Hello Hey);

print_line(@parole);
print "Done\n";

# Our subroutine accepts an array, then prints the
# value of each element appended to "Perl World."
sub print_line
   {
   my @parole = @_;
   foreach (@parole)
      {
      print "$_ Perl World\n";
      }
   }

Now run it under the debugger and step through the program one statement at a time using the n (next) command:

% perl -dw debug.pl
main::(debug.pl:4):     my @parole = qw(Salutations Hello Hey);
  DB<1> n
main::(debug.pl:6):     &print_line(@parole);
  DB<1> n
Salutations Perl World
Hello Perl World
Hey Perl World
main::(debug.pl:7):     print "Done\n";
  DB<1> n
Done
Debugged program terminated.  Use q to quit or R to restart, use
O inhibit_exit to avoid stopping after program termination, h
q, h R or h O to get additional info.
  DB<1> q
                                        

Before the prompt, the debugger prints the source line(s) containing the statement to be executed in the next step. (If you have more than one executable statement in a line, it prints the line each time you type n until it's done executing all the statements on the line.) Notice the output of our program going to the terminal is intermingled with the debugger text. Notice also when we called print_line(@parole) , we executed all the statements in the subroutine before we got another prompt.

(From now on, we won't reproduce the optimistic Debugged program terminated blurb printed by the debugger.)

Suppose we wanted to step through the code inside subroutines like print_line . That's the reason for s (single step). Let's see how it's used, along with another handy stepping command, r (return):

% perl -d debug.pl
main::(debug.pl:4):     my @parole = qw(Salutations Hello Hey);
  DB<1> n
main::(debug.pl:6):     print_line(@parole);
  DB<1> s
main::print_line(debug.pl:13):     my @parole = @_;
  DB<1> n
main::print_line(debug.pl:14):     foreach (@parole)
main::print_line(debug.pl:15):        {
  DB<1>
main::print_line(debug.pl:16):        print "$_ Perl World\n";
  DB<1> r
Salutations Perl World
Hello Perl World
Hey Perl World
void context return from main::print_line
main::(debug.pl:7):     print "Done\n";
  DB<1> s
Done
Debugged program terminated.

The effect of r is to execute all the code up to the end of the current subroutine. (All these command letters are copied from existing popular Unix command line debuggers and are mnemonic -- n ext, s tep, r eturn). In addition, note that just hitting carriage return as a command repeats the last n or s command (and if there hasn't been one yet, it does nothing).

7.2.2. Examining Variables: p, x, V

Stepping through code is dandy, but how do we check our variables' values? Use either p expression to print the result of the expression (which is equivalent to print ing to the filehandle $DB::OUT , so expression is put in list context) or x variable , which prints a variable in a pleasantly formatted form, following references. Once again, with the simple program:

% perl -wd debug.pl
main::(debug.pl:4):     my @parole = qw(Salutations Hello Hey);
  DB<1> p
                                                @parole
  DB<2> n
main::(debug.pl:6):     print_line(@parole);
  DB<2> p
                                                @parole
SalutationsHelloHey
  DB<3> x
                                                @parole
0  'Salutations'
1  'Hello'
2  'Hey'

In the first command, we instruct the debugger to print the value of @parole . However, the @parole assignment has yet to execute, so nothing comes out. Step past the assignment and then print the value with p ; we see the current state of the array in a list format. Print the array value with x , and we see the individual elements formatted with array indices (a pretty print).

This might look familiar if you've been playing with the Data::Dumper module we referenced in Chapter 5 . In fact, the output of x is intentionally very similar.

You can see all of the dynamic variables in a given package (default: main:: ) with the V command. This isn't as useful as it sounds because, unlike the x or p commands, it won't show you any lexical variables (which you declared with my ). Yet you want to make as many of your variables as possible lexical ones (see Perl of Wisdom #8). Unfortunately there is no (easy) way to dump out all the lexical variables in a package, so you're reduced to printing the ones you know about.

A common problem is running off the end of the program and getting the Debugged program terminated message. At that point, all your variables have been destroyed. If you want to inspect the state of variables after the last line of your program has executed, add a dummy line (a 1 by itself will work) so that you can set a breakpoint on it.

Tip

when e x amining a hash, examine a reference to it instead. This lets the x command see the datatype you're inspecting instead of being handed the list that it evaluates to, and it can format it more appealingly:

  DB<1> %h = (Craig   => 'Stirling', \
                                                Sharron => 'Macready', Richard => 'Barrett');
  DB<2> x
                                                %h
0  'Sharron'
1  'Macready'
2  'Craig'
3  'Stirling'
4  'Richard'
5  'Barrett'
  DB<3> x
                                                \%h
0  HASH(0x8330d5c)
   'Craig' => 'Stirling'
   'Richard' => 'Barrett'
   'Sharron' => 'Macready'

Examine references to hashes instead of the hashes themselves in the debugger to get well-formatted output.


7.2.3. Examining Source: l, -, w,

Sometimes you want more of the context of your program than just the current line. The following commands show you parts of your source code:

l List successive windows of source code starting from the current line about to be executed.
l x + y List + 1 lines of source starting from line x.
l x - y List source lines through y.
- List successive windows of source code before the current line.
w List a window of lines around the current line.
w line List a window of lines around line.
. Reset pointer for window listings to current line.

Source lines that are breakable (i.e. can have a breakpoint inserted before them -- see the following section) have a colon after the line number.

7.2.4. Playing in the Sandbox

Since the debugger is a full-fledged Perl environment, you can type in Perl code on the fly to examine its effects under the debugger; [1] some people do this as a way of testing code quickly without having to enter it in a script or type in everything perfectly before hitting end-of-file. (You just saw us do this at the end of section 7.2.2 .)

[1] So, you might wonder, how would you enter Perl code which happened to look like a debugger command (because you'd defined a subroutine l , perhaps)? In versions of Perl prior to 5.6.0, if you enter leading white space before text, the debugger assumes it must be Perl code and not a debugger command. So be careful not to hit the space bar by accident before typing a debugger command. This was no longer true as of version 5.6.0.

Type perl -de 0 to enter this environment. [2] Let's use this as a sandbox for testing Perl constructs:

[2] There are many expressions other than 0 that would work equally well, of course. Perl just needs something innocuous to run.

% perl -de 0
DB<1> $_ = 'What_do*parens-in=split+do%again?';
  DB<2> @a = split /(\W+)/;
  DB<3> x
                                                @a
0  'What_do'
1  '*'
2  'parens'
3  '-'
4  'in'
5  '='
6  'split'
7  '+'
8  'do'
9  '%'
10  'again'
11  '?'

You can even use this feature to change the values of variables in a program you are debugging, which can be a legitimate strategy for seeing how your program behaves under different circumstances. If the way your program constructs the value of some internal variable is complex and it would require numerous changes in the input to have it form the variable differently, then a good way of playing "What if?" is to stop the program at the right place in the debugger and change the value by hand. How would we stop it? Let's see

7.2.5. Breakpointing: c, b, L

An important feature of a debugger is the ability to allow your program to continue executing until some condition is met. The most common such condition is the arrival of the debugger at a particular line in your source. You can tell the Perl debugger to run until a particular line number with the c (for continue) command:

main::(debug.pl:4):     my @parole = qw(Salutations Hello Hey);
  DB<1> c
                                                16
main::print_line(debug.pl:16):        print "$_ Perl World\n";
  DB<2>

What the debugger actually did was set a one-time breakpoint at line 16 and then executed your code until it got there. If it had hit another breakpoint earlier, it would have stopped there first.

So what's a breakpoint? It's a marker set by you immediately before a line of code, invisible to anyone but the perl debugger, which causes it to halt when it gets there and return control to you with a debugger prompt. If you have a breakpoint set at a line of code that gets printed out with one of the source examination commands listed earlier, you'll see a b next to it. It's analogous to putting a horse pill in the trail of bread crumbs the mouse follows so the mouse gets indigestion and stops to take a breather (we really have to give up this metaphor soon).

You set a breakpoint with the b command; the most useful forms are b line or b subroutine to set a breakpoint either at a given line number or immediately upon entering a subroutine. To run until the next breakpoint, type c . To delete a breakpoint, use d line to delete the breakpoint at line number line or D to delete all breakpoints.

In certain situations you won't want to break the next time you hit a particular breakpoint, but only when some condition is true, like every hundredth time through a loop. You can add a third argument to b specifying a condition that must be true before the debugger will stop at the breakpoint. For example,

Code View: Scroll / Show All
main::(debug.pl:4):   my @parole = qw(Salutations Hello Hey);
  DB<1> l
4==>    my @parole = qw(Salutations Hello Hey);
5
6:      print_line(@parole);
7:      print "Done\n";
8
9       # Our subroutine which accepts an array, then prints
10      # the value of each element appended to "Perl World."
11      sub print_line
12         {
13:        my @parole = @_;
  DB<1> l
14:        foreach (@parole)
15            {
16:           print "$_ Perl World\n";
17            }
18         }
  DB<1> b
                                                16 /Hey/
  DB<2> c
Salutations Perl World
Hello Perl World
main::print_line(debug.pl:16):        print "$_ Perl World\n";
  DB<2> p
Hey


                                        

Notice that we've demonstrated several things here: the source listing command l , the conditional breakpoint with the criterion that $_ must match /Hey/ , and that $_ is the default variable for the p command (because p just calls print ).

The capability of the debugger to insert code that gets executed in the context of the program being debugged does not exist in compiled languages and is a significant example of the kind of thing that is possible in a language as well designed as Perl.

The command L lists all breakpoints.

7.2.6. Taking Action: a, A

An even more advanced use of the facility to execute arbitrary code in the debugger is the action capability. With the a command (syntax: a line code ), you can specify code to be executed just before a line would be executed. (If a breakpoint is set for that line, the action executes first; then you get the debugger prompt.) The action can be arbitrarily complicated and, unlike this facility in debuggers for compiled languages, lets you reach into the program itself:

main::(debug.pl:4):     my @parole = qw(Salutations Hello Hey);
  DB<1> a
                                                16 s/Hey/Greetings/
  DB<2> c
Salutations Perl World
Hello Perl World
Greetings Perl World
Done
Debugged program terminated.

L also lists any actions you have created. Delete all the installed actions with the A command. This process is commonly used to insert tracing code on the fly. For example, suppose you have a program executing a loop containing way too much code to step through, but you want to monitor the state of certain variables each time it goes around the loop. You might want to confirm what's actually being ordered in a shopping cart application test (looking at just a fragment of an imaginary such application here):

Code View: Scroll / Show All
  DB<1> l
                                                79-91
79:     while (my $item = shift @shopping_basket)
80         {
81:        if ($item->in_stock)
82            {
83:           $inventory->remove($item);
84:           $order->add($item);
85            }
86         else
87            {
88:           $order->back_order($item);
89:           $inventory->order($item);
90            }
91         }
  DB<2> a
                                                81 printf "Item: %25s, Cost: %5.2f\n",
                                                $item->name, $item->cost
  DB<3> c
                                                92
Item:          Forbidden Planet, Cost: 24.50
Item:      Kentucky Fried Movie, Cost: 29.95
Item:                Eraserhead, Cost: 14.75
main::(cart.pl:92):    $customer->charge($order->total);
  DB<3>


                                        

7.2.7. Watch It:

Suppose you want to break on a condition that is dictated not by a particular line of code but by a change in a particular variable. This is called a watchpoint, and in Perl you set it with the W command followed by the name of a variable. [3]

[3] In fact, Perl can monitor anything that evaluates to an lvalue, so you can watch just specific array or hash entries, for example.

Let's say you're reading a file of telephone numbers and to whom they belong into a hash, and you want to stop once you've read in the number 555-1212 to inspect the next input line before going on to check other things:

main::(foo:1):  my %phone;
  DB<1> l
                                                1-5
1==>    my %phone;
2:      while (<>) {
3:        my ($k, $v) = split;
4:        $phone{$k} = $v;
5       }
  DB<2> W
                                                $phone{'555-1212'}
  DB<3> c
Watchpoint 0:   $phone{'555-1212'} changed:
    old value:  undef
    new value:  'Information'
main::(foo:2):  while (<>) {
  DB<3> n
main::(foo:3):    my ($k, $v) = split;
  DB<3> p
555-1234 Weather

Delete all watchpoints with a blank W command.

7.2.8. Trace:

The debugger's t command provides a trace mode for those instances that require a complete trace of program execution. Running the program with an active trace mode:

Code View: Scroll / Show All
% perl -wd debug.pl
main::(debug.pl:4):     my @parole = qw(Salutations Hello Hey);
  DB<1> t
Trace = on
  DB<1> n
main::(debug.pl:6):     print_line(@parole);
  DB<1> n
main::print_line(debug.pl:13):     my @parole = @_;
main::print_line(debug.pl:14):     foreach (@parole)
main::print_line(debug.pl:15):        {
main::print_line(debug.pl:16):        print "$_ Perl World\n";
Salutations Perl World
main::print_line(debug.pl:14):     foreach (@parole)
main::print_line(debug.pl:15):        {
main::print_line(debug.pl:16):        print "$_ Perl World\n";
Hello Perl World
main::print_line(debug.pl:14):     foreach (@parole)
main::print_line(debug.pl:15):        {
main::print_line(debug.pl:16):        print "$_ Perl World\n";
Hey Perl World
main::print_line(debug.pl:14):     foreach (@parole)
main::print_line(debug.pl:15):        {
main::(debug.pl:7):     print "Done\n";


                                        

Notice that trace mode causes the debugger to output the call tree when execution enters the print_line subroutine.

7.2.9. Programmatic Interaction with the Debugger

You can put code in your program to force a call to the debugger at a particular point. For instance, suppose you're processing a long input file line by line and you want to start tracing when it reaches a particular line. You could set a conditional breakpoint, but you could also extend the semantics of your input by creating "enable debugger" lines. Consider the following code:

while (<INPUT>)
   {
   $DB::trace = 1, next if /debug/;
   $DB::trace = 0, next if /nodebug/;
   # more code
   }

When run under the debugger, this enables tracing when the loop encounters an input line containing "debug" and ceases tracing upon reading one containing " nodebug ". You can even force the debugger to breakpoint by setting the variable $DB::single to 1 , which also happens to provide a way you can debug code in BEGIN blocks (which otherwise are executed before control is given to the debugger).

7.2.10. Optimization

Although the Perl debugger displays lines of code as it runs, it's important to note that these are not what actually executes. Perl internally executes its compiled opcode tree, which doesn't always have a contiguous mapping to the lines of code you typed, due to the processes of compilation and optimization. If you have used interactive debuggers on C code in the past, you may be familiar with this process.

When debugging C programs on VAX/VMS, it was common for me to want to examine an important variable only to get the message that the variable was not in memory and had been "optimized away."


Perl has an optimizer to do as good a job as it can -- in the short amount of time people will wait for compilation -- of taking shortcuts in the code you've given it. For instance, in a process called constant folding, it does things like build a single string in places where you concatenate various constant strings together so that the concatenation operator need not be called at run-time.

The optimization process also means that perl may execute opcodes in an order different from the order of statements in your program, and therefore when the debugger displays the current statement, you may see it jump around oddly. As recently as version 5.004_04 of perl, this could be observed in a program like the following:

1   my @a = qw(one two three);
2   while ($_ = pop @a)
3      {
4      print "$_\n";
5      }
6   1;

See what happens when we step through this, again using perl 5.004_04 or earlier:

main::(while.pl:1):   my @a = qw(one two three);
  DB<1> n
main::(while.pl:6):   1;
  DB<1>
main::(while.pl:4):     print "$_\n";
  DB<1>
three
main::(while.pl:2):   while ($_ = pop @a)
  DB<1>
main::(while.pl:4):     print "$_\n";
  DB<1>
two

In fact, if we set a breakpoint for line 6 and ran to it, we'd get there before the loop executed at all. So it's important to realize that under some circumstances, what the debugger tells you about where you are can be confusing. If this inconveniences you, upgrade.

7.2.11. Another "Gotcha"

If you set a lexical variable as the last statement of a block, there is no way to see what it was set to if the block exits to a scope that doesn't include the lexical. Why would code do that? In a word, closures. For example,

{                  # Start a closure-enclosing block
my $spam_type;     # This lexical will outlive its block
sub type_spam
   {
   # ...
   $spam_type = $spam_types[complex_func()];
   }
}

In this case, either type_spam or some other subroutine in the closure block would have a good reason for seeing the last value of $spam_type . But if you're stepping through in the debugger, you won't see the value it gets set to on the last line because, after the statement executes, the debugger pops out to a scope where $spam_type is not in scope (unless type_spam() was called from within the enclosing block). Unfortunately, in this case, if the result of the function is not used by the caller, you're out of luck.

Hack 55. Show Source Code on Errors

From O'Reilly Perl Hacks books

Don't guess which line is the problem-see it!

Debugging errors and warning messages isn't often fun. Instead, it can be tedious. Often even finding the problem takes too long.

Perl can reveal the line number of warnings and errors (with warn and die and the warnings pragma in effect); why can't it show the source code of the affected line?

The Hack

The code to do this is pretty easy, if unsubtle:

Code View: Scroll
package SourceCarp;

use strict;
use warnings;

sub import
{
    my ($class, %args) = @_;

    $SIG{__DIE__}  = sub { report( shift, 2 ); exit } if $args{fatal};
    $SIG{__WARN__} = \\&report                         if $args{warnings};
}

sub report
{
    my ($message, $level)  = @_;
    $level               ||= 1;
    my ($filename, $line)  = ( caller( $level - 1 ) )[1, 2];
    warn $message, show_source( $filename, $line );
}

sub show_source
{
    my ($filename, $line) = @_;
    return '' unless open( my $fh, $filename );

    my $start = $line - 2;
    my $end   = $line + 2;

    local $.;
    my @text;
    while (<$fh>)
    {
        next unless $. >= $start;
        last if     $. >  $end;
        my $highlight   = $. = = $line ? '*' : ' ';
        push @text, sprintf( "%s%04d: %s", $highlight, $., $_ );
    }

    return join( '', @text, "\\n" );
}

1; 

The magic here is in three places. report( ) looks at the call stack leading to its current position, extracting the name of the file and the line number of the calling code. It's possible to call this function directly with a message to display (and an optional level of calls to ignore).

show_source( ) simply reads the named file and returns a string containing two lines before and after the numbered line, if possible. It also highlights the specific line with an asterisk in the left column. Note the localization and use of the $. magic variable to count the current line in the file.

import( ) adds global handlers for warnings and exceptions, if requested from the calling module. The difference between the handlers is that when Perl issues a lexical warning, it doesn't affect the call stack in the same way that it does when it throws an exception.

Running the Hack

This short program shows all three ways of invoking SourceCarp:

#!/usr/bin/perl

use strict;
use warnings;

use lib 'lib';
use SourceCarp fatal => 1, warnings => 1;

# throw warning
open my $fh, '<', '/no/file';
print {$fh}...

# report from subroutine
report_with_level( );

sub report_with_level
{
    SourceCarp::report( "report caller, not self\\n", 2 );
}

# throw error
die "Oops!";

Hacking the Hack

There's no reason to limit your error and warning reporting to showing the file context around the calling line. caller( ) offers much more information, including the variables passed to each function in certain circumstances. It's possible to provide and present this information in a much more useful manner.

See perldoc -f caller.

Overriding the global __WARN__ and __DIE__ handlers is serious business as it can interfere with large programs. A more robust implementation of this hack might work nicely with Carp, not only because it is more widely compatible, but also because that module offers more features. Another possibility is to integrate this code somehow with Log::Log4perl.

[Jul 09, 2012] 11. Using the perl Debugger

From Perl for Perl Newbies - Part 2 by Shlomi Fish

[Jul 09, 2012] Perl Debugger

Breakpoints

One of the most powerful features of most debuggers is their ability to stop at a certain line of code, or to stop when a certain condition is met. The simplest type of breakpoint is via a line number. Suppose we are debugging the file testArgs.pl, and we want to stop as soon as we enter the subroutine "change". We look at the source code with an editor and see that subroutine starts at line 24. We can set the breakpoint via the command

b 24

At any time we can list all of our breakpoints (and actions, but more on that later) via the L command. In this case we'd get the output:

  DB<2> L
testArgs.pl:
 24:        print "In change, the formal parameter is $_[0].\n";
   break if (1)
  DB<2>

Now we can just let the program run via the c (continue) command. The program will stop at the next breakpoint. We get the output:

  DB<2> c
In main, the variable arg is 1 before any subroutine calls.
main::change(testArgs.pl:24):       print "In change, the formal parameter is $_
[0].\n";
  DB<2>

which is right where we wanted to be. You might want to try the v (view) command to view the lines of code immediately surrounding this one, and then use the p command to view the values of variables:

  DB<2> v
21==>   #Notice that the subroutine accesses the parameter directly via the @_ variable.
22      #I.e., it does not place the value in a variable.
23      sub change {
24:b        print "In change, the formal parameter is $_[0].\n";
25:         $_[0] += 1;
26:         print "In change, after adding, the parameter is $_[0].\n";
27      }
28
29      #In this subroutine, we stored the formal parameter in a variable.  The assignment
30      #statement makes a copy, so changes to this variable do not affect the formal
  DB<2> p $_[0]
1
  DB<3> p "@_"
1

An easier way to set a breakpoint at the beginning of a subroutine is to simply provide its name as the argument to the b command:

  DB<1> b change
  DB<2> L
testArgs.pl:
 24:        print "In change, the formal parameter is $_[0].\n";
   break if (1)
  DB<2>

Notice that the L command gives the same output. Again, use the c command to continue to this breakpoint. Now that we are at a breakpoint we can look at the activation (or "traceback" or "callback") stack via the T command. Here that would yield:

  DB<2> c
In main, the variable arg is 1 before any subroutine calls.
main::change(testArgs.pl:24):       print "In change, the formal parameter is $_
[0].\n";
  DB<2> T
. = main::change(1) called from file `testArgs.pl' line 11
  DB<2>

which identifies the line we are at, and how we got here.

An even fancier kind of breakpoint is obtained by specifying a condition. The syntax is the same as above except that we append an extra argument to the b command, a Perl expression that will be evaluated each time the program's execution gets to the breakpoint's line. Only if the expression evaluates to true does the debugger halt there. Let's look at an example. Suppose we run the debugger on the program testDebugger.pl. Upon starting the debugger we want to break at the top of the while loop, but only when our iteration variable $arg has exceeded a value of 5. The following shows how we set this breakpoint condition:

main::(testDebugger.pl:8):      looper();
  DB<1> v
5==>    # This program demonstrates the Perl debugger.
6:      use strict;
7
8:      looper();
9
10      sub looper {
11:         my $arg = 0;
12:         while ($arg < 10) {
13:             ++$arg;
14          }
  DB<1> b 12 ($arg > 5)
  DB<2> c
main::looper(testDebugger.pl:12):           while ($arg < 10) {
  DB<2> p $arg
6
  DB<3>

As you can see, the value of $arg is 6, i.e. greater than 5, when the debugger suspends execution. By the way, we can now explain some of the output we saw from an earlier use of the L command above. Using the L command here yields:

  DB<3> L
testDebugger.pl:
 12:        while ($arg < 10) {
   break if (($arg > 5))
  DB<3>

You can see the break condition for line 12 listed there. Now you can probably understand why when we used L earlier, we had this output (repeated here):

  DB<1> b change
  DB<2> L
testArgs.pl:
 24:        print "In change, the formal parameter is $_[0].\n";
   break if (1)
  DB<2>

The "break if (1)" is showing a condition of "1", i.e. a condition which is always true (since any numeric value other than 0 is considered "true"). Thus that breakpoint will always trigger whenever execution reaches line 24.

Watches

It is very common to want to suspend the program when the value of a variable is changed. The w (watch) command does this. The usual usage is w variableName. Let's go debug testArgs.pl again. This time, at the beginning of the debugging session we do a w $arg and then c (continue) the program. We get this:

  DB<1> w $arg
  DB<2> c
Watchpoint 0:   $arg changed:
        old value:      undef
        new value:      '1'
main::(testArgs.pl:10): print "In main, the variable arg is $arg before any subroutine calls.\n";
  DB<2>

As you can see the first break occurs just after execution of line 9,

my ($arg) = 1;

The value of the variable has changed from "undefined" to 1. Now we'll let the session c (continue) again to get:

  DB<2> c
In main, the variable arg is 1 before any subroutine calls.
In change, the formal parameter is 1.
Watchpoint 0:   $arg changed:
        old value:      '1'
        new value:      '2'
main::change(testArgs.pl:26):       print "In change, after adding, the paramete
r is $_[0].\n";
  DB<2> v
23==>   sub change {
24:         print "In change, the formal parameter is $_[0].\n";
25:         $_[0] += 1;
26:         print "In change, after adding, the parameter is $_[0].\n";
27      }
28
29      #In this subroutine, we stored the formal parameter in a variable.  The assignment
30      #statement makes a copy, so changes to this variable do not affect the formal
31      #parameter, and thus don't affect the actual parameter either.
32      sub change2 {
  DB<2>

The debugger has suspended execution just pas the increment line. Note that this line doesn't even explicitly mention "$arg", but $_[0] is a reference (alias) to that value, so execution suspends. Oh, and yes, you may append conditions to watch commands too.

You can clear watches via the W command. Likewise you can clear breakpoints via the B command. (These are the commands for cygwin's Perl. Canonical Perl uses the d command instead of B. Cygwin's syntax is more consistent.)

[May 29, 2012] brian's Guide to Solving Any Perl Problem Appendix B

See also perldebtut -- Perl debugging tutorial
Mastering Perl -- O'Reilly Media
What is the warning?
Perl can warn you about a lot of questionable constructs. Turn on warnings and help Perl help you.

You can use perl's -w switch in the shebang line:

#!/usr/bin/perl -w

You can turn on warnings from the command line:

$ perl -w program.pl

Lexical warnings have all sorts of interesting features. See the warnings pragma documentation for the details:

use warnings;

If you don't understand a warning, you can look up a verbose version of the warning in perldiag or you can use the diagnostics pragma in your code:

use diagnostics;
Solve the first problem first!
After you get error or warning messages from perl, fix the first message then see if perl still issues the other messages. Those extra messages may be artifacts of the first problem.
Look at the code before the line number in the error message!
Perl gives you warning messages when it gets worried and not before. By the time perl gets worried, the problem has already occurred and the line number perl is on may actually be after the problem. Look at the couple of expressions before the line number in the warning.
Is the value what you think it is?
Don't guess! Verify everything! Actually examine the value right before you want to use it in an expression. The best debugger in the universe is print:
print STDERR "The value is [$value]\n";

I enclose $value in brackets so I can see any leading or trailing whitespace or newlines. If I have anything other than a scalar, I use Data::Dumper to print the data structures:

require Data::Dumper;

print STDERR "The hash is ", Data::Dumper::Dumper( %hash ), "\n";

If the value is not what you think it is, back up a few steps and try again! Do this until you find the point at which the value stops being what you think it should be!

You can also use the built-in Perl debugger with perl's -d switch. See perldebug for details:

perl -d program.pl

You can also use other debuggers or development environments, such as ptkdb (a graphical debugger based on Tk) or Komodo (ActiveState's Perl IDE based on Mozilla). I cover debugging in Chapter 4, Debugging Perl.

Are you using the function correctly?
I have been programming Perl for quite a long time and I still look at perlfunc almost every day. Some things I just cannot keep straight, and sometimes I am so sleep-deprived that I take leave of all of my senses and wonder why sprintf() does not print to the screen.

You can look up a particular function with the perldoc command and its -f switch.

perldoc -f function_name

If you're using a module, check the documentation to make sure you are using it in the right way. You can check the documentation for the module using perldoc:

perldoc Module::Name
Are you using the right special variable?
Again, I constantly refer to perlvar. Well, not really since I find The Perl Pocket Reference much easier to use.
Do you have the right version of the module?
Some modules change behavior between versions. Do you have the version of the module that you think you have? You can check the installed module version with a simple perl one-liner:
perl -MModule::Name -le 'print Module::Name->VERSION';

If you read most of your documentation off of the local machine, like at http://perldoc.perl.org or http://search.cpan.org, then you are more likely to encounter version differences in documentation.

Have you made a small test case?
If you're trying something new or think a particular piece of code is acting funny, write the shortest possible program to do just that piece. This removes most of the other factors from consideration. If the small test program does what it thinks it does, the problem probably isn't in that code. If the program doesn't do what you think it should, then perhaps you have found your problem.
Did you check the environment?
Some things depend on environment variables. Are you sure that they are set to the right thing? Is your environment the same that the program will see when it runs? Remember that programs intended for CGI programs or cron jobs may see different environments than those in your interactive shell, especially on different machines.

Perl stores the environment in %ENV. If you need one of those variables, be ready to supply a default value if it does not exist, even if only for testing.

If you still have trouble, inspect the environment:

require Data::Dumper;
print STDERR Data::Dumper::Dumper( \%ENV );
Have you checked Google?
If you have a problem, somebody else has probably already had that problem. See if one of those other people posted something to the Usenet group comp.lang.perl.misc by searching Google Groups (http://groups.google.com). The difference between people who ask questions on Usenet and those who answer them is the ability to use Google Groups effectively.
Have you profiled the application?
If you want to track down the slow parts of the program, have you profiled it? Let Devel::SmallProf do the heavy lifting for you. It counts the times perl executes a line of code as well as how long it takes and prints a nice report. I cover profiling in Chapter 5, Profiling Perl.
Which test fails?
If you have a test suite, which test fails? You should be able to track down the error very quickly since each test will only exercise a little bit of code.

If you don't have a test suite, why not make one? If you have a really small program or this is a one-off program, then I'm not going to make you write a couple of tests. Anything other than that could really benefit from some test programs. The Test::More module makes this extremely simple, and if you program your script as a modulino as in Chapter 18, Modules As Programs, you have all the tools of module development available for your program.

Did you talk to the bear?
Explain your problem aloud. Actually say the words.

For a couple of years I had the pleasure of working with a really good programmer who could solve almost anything. When I got really stuck I would walk over to his desk and start to explain my problem. Usually I wouldn't make it past the third sentence without saying, "Nevermind-I got it." He almost never missed either.

Since you'll probably need to do this so much, I recommend some sort of plush toy to act as your Perl therapist so you don't annoy your colleagues. I have a small bear that sits on my desk and I explain problems to him. My girlfriend does not even pay attention when I talk to myself anymore.

Does the problem look different on paper?
You have been staring at the computer screen, so maybe a different medium will let you look at things in a new way. Try looking at a printout of your program.
Have you watched The Daily Show with Jon Stewart?
Seriously. Perhaps you do not like Jon Stewart, so choose something else. Take a break. Stop thinking about the problem for a bit and let your mind relax. Come back to the problem later and the fix may become immediately apparent.
Have you packed your ego?
If you've have made it this far, the problem may be psychological. You might be emotionally attached to a certain part of the code, so you do not change it. You might also think that everyone else is wrong but you. When you do that, you don't seriously consider the most likely source of bugs-yourself. Do not ignore anything. Verify everything.

If you enjoyed this excerpt, buy a copy of Mastering Perl

[Mar 07, 2012] Debugging Perl with ease

Cultured Perl

The Perl debugger comes with its own help ('h' or 'h h', for the long and short help screens, respectively). The perldoc perldebug page (type "perldoc perldebug" at your prompt) has a more complete description of the Perl debugger.

So let's start with a buggy program and take a look at how the Perl debugger works. First, it'll attempt to print the first 20 lines in a file.

 #!/usr/bin/perl -w

 use strict;

 foreach (0..20)
 {
  my $line =
;
  print "$_ : $line";
 }

When run by itself, buggy.pl fails with the message: "Use of uninitialized value in concatenation (.) at ./buggy.pl line 8, line 9." More mysteriously, it prints "9:" on a line by itself and waits for user input.

Now what does that mean? You may already have spotted the bugbear that came along when we fired up the Perl debugger.

First let's simply make sure the bug is repeatable. We'll set an action on line 8 to print $line where the error occurred, and run the program.

 > perl -d ./buggy.pl buggy.pl

 Default die handler restored.

 Loading DB routines from perl5db.pl version 1.07
 Editor support available.

 Enter h or `h h' for help, or `man perldebug' for more help.

 main::(./buggy.pl:5):   foreach (0..20)
 main::(./buggy.pl:6):   {
   DB<1>  use Data::Dumper

   DB<1>  a 8 print 'The line variable is now ', Dumper $line
The Data::Dumper module loads so that the autoaction can use a nice output format. The autoaction is set to do a print statement every time line 8 is reached. Now let's watch the show.
  DB
 c
 The line variable is now $VAR1 = '#!/usr/bin/perl -w
 ';
 0 : #!/usr/bin/perl -w
 The line variable is now $VAR1 = '
 ';
 1 :
 The line variable is now $VAR1 = 'use strict;
 ';
 2 : use strict;
 The line variable is now $VAR1 = '
 ';
 3 :
 The line variable is now $VAR1 = 'foreach (0..20)
 ';
 4 : foreach (0..20)
 The line variable is now $VAR1 = '{
 ';
 5 : {
 The line variable is now $VAR1 = ' my $line =
;
 ';
 6 :  my $line =
;
 The line variable is now $VAR1 = ' print "$_ : $line";
 ';
 7 :  print "$_ : $line";
 The line variable is now $VAR1 = '}
 ';
 8 : }
 The line variable is now $VAR1 = undef;
 Use of uninitialized value in concatenation (.) at ./buggy.pl line 8, <> line 9.
 9 :

It's clear now that the problem occurred when the line variable was undefined. Furthermore, the program waited for more input. And pressing the Return key eleven more times created the following output:
The line variable is now $VAR1 = '
';
10 :
The line variable is now $VAR1 = '
';
11 :
The line variable is now $VAR1 = '
';
12 :
The line variable is now $VAR1 = '
';
13 :
The line variable is now $VAR1 = '
';
14 :
The line variable is now $VAR1 = '
';
15 :
The line variable is now $VAR1 = '
';
16 :
The line variable is now $VAR1 = '
';
17 :
The line variable is now $VAR1 = '
';
18 :
The line variable is now $VAR1 = '
';
19 :
The line variable is now $VAR1 = '
';
20 :
Debugged program terminated.  Use q to quit or R to restart,
  use O inhibit_exit to avoid stopping after program termination,
  h q, h R or h O to get additional info. 
  DB<3>

By now it's obvious that the program is buggy because it unconditionally waits for 20 lines of input, even though there are cases in which the lines will not be there. The fix is to test the $line after reading it from the filehandle:
#!/usr/bin/perl -w
use strict;
foreach (0..20)
{
 my $line =
;
 last unless defined $line;		# exit loop if $line is not defined
 print "$_ : $line";
}

As you see, the fixed program works properly in all cases!

[Jan 22, 2009] DB - programmatic interface to the Perl debugging API (draft ...

DB - programmatic interface to the Perl debugging API (draft, subject to change) ... like debugging with a command line and GUI at the same time, debugging debuggers etc. ... This module attempts to be squeaky clean w.r.t use strict; ...
sunsite.ualberta.ca/Documentation/Misc/perl-5.6.1/lib/DB.html - 12k - Cached - Similar pages

[Mar 13, 2007] Programming in Perl - Debugging

On this page, I will post aides and tools that Perl provides which allow you to more efficently debug your Perl code. I will post updates as we cover material necessary for understanding the tools mentioned.
CGI::Dump
Dump is one of the functions exported in CGI.pm's :standard set. It's functionality is similar to that of Data::Dumper. Rather than pretty-printing a complex data structure, however, this module pretty-prints all of the parameters passed to your CGI script. That is to say that when called, it generates an HTML list of each parameter's name and value, so that you can see exactly what parameters were passed to your script. Don't forget that you must print the return value of this function - it doesn't do any printing on its own.
use CGI qw/:standard/;
print Dump;
Benchmark
As you know by now, one of Perl's mottos is "There's More Than One Way To Do It" (TMTOWTDI ©). This is usually a Good Thing, but can occasionally lead to confusion. One of the most common forms of confusion that Perl's verstaility causes is wondering which of multiple ways one should use to get the job done most quickly.

Analyzing two or more chunks of code to see how they compare time-wise is known as "Benchmarking". Perl provides a standard module that will Benchmark your code for you. It is named, unsurprisingly, Benchmark. Benchmark provides several helpful subroutines, but the most common is called cmpthese(). This subroutine takes two arguments: The number of iterations to run each method, and a hashref containing the code blocks (subroutines) you want to compare, keyed by a label for each block. It will run each subroutine the number of times specified, and then print out statistics telling you how they compare.

For example, my solution to ICA5 contained three different ways of creating a two dimensional array. Which one of these ways is "best"? Let's have Benchmark tell us:

#!/usr/bin/perl
use strict;
use warnings;
use Benchmark 'cmpthese';

sub explicit {
    my @two_d = ([ ('x') x 10 ],
                 [ ('x') x 10 ],
                 [ ('x') x 10 ],
                 [ ('x') x 10 ],
                 [ ('x') x 10 ]);
}

sub new_per_loop {
    my @two_d;
    for (0..4){
        my @inner = ('x') x 10;
        push @two_d, \@inner;
    }
}

sub anon_ref_per_loop {
    my @two_d;
    for (0..4){
        push @two_d, [ ('x') x 10 ];
    }
}

sub nested {
    my @two_d;
    for my $i (0..4){
        for my $j (0..9){
            $two_d[$i][$j] = 'x';
        }
    }
}
cmpthese (10_000, {
                 'Explicit'           => \&explicit,
                 'New Array Per Loop' => \&new_per_loop,
                 'Anon. Ref Per Loop' => \&anon_ref_per_loop,
                 'Nested Loops'       => \&nested,
             }
      );
The above code will print out the following statistics (numbers may be slightly off, of course):
Benchmark: timing 10000 iterations of Anon. Ref Per Loop, Explicit, Nested Loops, New Array Per Loop...
Anon. Ref Per Loop:  2 wallclock secs ( 1.53 usr +  0.00 sys =  1.53 CPU) @ 6535.95/s (n=10000)
Explicit:  1 wallclock secs ( 1.24 usr +  0.00 sys =  1.24 CPU) @ 8064.52/s (n=10000)
Nested Loops:  4 wallclock secs ( 4.01 usr +  0.00 sys =  4.01 CPU) @ 2493.77/s (n=10000)
New Array Per Loop:  2 wallclock secs ( 1.76 usr +  0.00 sys =  1.76 CPU) @ 5681.82/s (n=10000)
                     Rate Nested Loops New Array Per Loop Anon. Ref Per Loop Explicit
Nested Loops       2494/s           --               -56%               -62%     -69%
New Array Per Loop 5682/s         128%                 --               -13%     -30%
Anon. Ref Per Loop 6536/s         162%                15%                 --     -19%
Explicit           8065/s         223%                42%                23%       --

The benchmark first tells us how many iterations of which subroutines it's running. It then tells us how long each method took to run the given number of iterations. Finally, it prints out the statistics table, sorted from slowest to fastest. The Rate column tells us how many iterations each subroutine was able to perform per second. The remaining colums tells us how fast each method was in comparison to each of the other methods. (For example, 'Explicit' was 223% faster than 'Nested Loops', while 'New Array Per Loop' is 13% slower than 'Anon. Ref Per Loop'). From the above, we can see that 'Explicit' is by far the fastest of the four methods. It is, however, only 23% faster than 'Ref Per Loop', which requires far less typing and is much more easily maintainable (if your boss suddenly tells you he'd rather have the two-d array be 20x17, and each cell init'ed to 'X' rather than 'x', which of the two would you rather had been used?).

You can, of course, read more about this module, and see its other options, by reading: perldoc Benchmark

Command-line options
Perl provides several command-line options which make it possible to write very quick and very useful "one-liners". For more information on all the options available, refer to perldoc perlrun
-e
This option takes a string and evaluates the Perl code within. This is the primary means of executing a one-liner
perl -e'print qq{Hello World\n};'
(In windows, you may have to use double-quotes rather than single. Either way, it's probably better to use q// and qq// within your one liner, rather than remembering to escape the quotes).
-l
This option has two distinct effects that work in conjunction. First, it sets $\ (the output record terminator) to the current value of $/ (the input record separator). In effect, this means that every print statement will automatically have a newline appended. Secondly, it auto-chomps any input read via the <> operator, saving you the typing necessary to do it.
perl -le 'while (<>){ $_ .= q{testing};  print; }'
The above would automatically chomp $_, and then add the newline back on at the print statement, so that "testing" appears on the same line as the entered string.
-w
This is the standard way to enable warnings in your one liners. This saves you from having to type use warnings;
-M
This option auto-uses a given module.
perl -MData::Dumper -le'my @foo=(1..10); print Dumper(\@foo);'
-n
This disturbingly powerful option wraps your entire one-liner in a while (<>) { ... } loop. That is, your one-liner will be executed once for each line of each file specified on the command line, each time setting $_ to the current line and $. to current line number.
perl -ne 'print if /^\d/' foo.txt beta.txt
The above one-line of code would loop through foo.txt and beta.txt, printing out all the lines that start with a digit. ($_ is assigned via the implicit while (<>) loop, and both print and m// operate on $_ if an explict argument isn't given).
-p
This is essentially the same thing as -n, except that it places a continue { print; } block after the while (<>) { ... } loop in which your code is wrapped. This is useful for reading through a list of files, making some sort of modification, and printing the results.
perl -pe 's/Paul/John/' email.txt
Open the file email.txt, loop through each line, replacing any instance of "Paul" with "John", and print every line (modified or not) to STDOUT
-i
This one sometimes astounds people that such a thing is possible with so little typing. -i is used in conjunction with either -n or -p. It causes the files specified on the command line to be edited "in-place", meaning that while you're looping through the lines of the files, all print statements are directed back to the original files. (That goes for both explicit prints, as well as the print in the continue block added by -p.)
If you give -i a string, this string will be used to create a back-up copy of the original file. Like so:
perl -pi.bkp -e's/Paul/John/' email.txt msg.txt
The above opens email.txt, replaces each line's instance of "Paul" with "John", and prints the results back to email.txt. The original email.txt is saved as email.txt.bkp. The same is then done for msg.txt

Remember that any of the command-line options listed here can also be given at the end of the shebang in non-one-liners. (But please do not start using -w in your real programs - use warnings; is still preferred because of its lexical scope and configurability).

Data::Dumper
The standard Data::Dumper module is very useful for examining exactly what is contained in your data structure (be it hash, array, or object (when we come to them) ). When you use this module, it exports one function, named Dumper. This function takes a reference to a data structure and returns a nicely formatted description of what that structure contains.
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;

my @foo = (5..10);
#add one element to the end of the array
#do you see the error?
$foo[@foo+1] = 'last';

print Dumper(\@foo);

When run, this program shows you exactly what is inside @foo:

$VAR1 = [
          5,
          6,
          7,
          8,
          9,
          10,
          undef,
          'last'
        ];

(I know we haven't covered references yet. For now, just accept my assertion that you create a reference by prepending the variable name with a backslash...)

__DATA__ & <DATA>
Perl uses the __DATA__ marker as a pseudo-datafile. You can use this marker to write quick tests which would involve finding a file name, opening that file, and reading from that file. If you just want to test a piece of code that requires a file to be read (but don't want to test the actual file opening and reading), place the data that would be in the input file under the __DATA__ marker. You can then read from this pseudo-file using <DATA>, without bothering to open an actual file:
#!/usr/bin/env perl
use strict;
use warnings;

while (my $line = <DATA>) {
  chomp $line;
  print "Size of line $.:  ", length $line, "\n";
}

__DATA__
hello world
42
abcde

The above program would print:

Size of line 1: 11
Size of line 2: 2
Size of line 3: 5
$.
The $. variable keeps track of the line numbers of the file currently being processed via a while (<$fh>) { ... } loop. More explicitly, it is the number of the last line read of the last file read.
__FILE__ & __LINE__
These are two special markers that return, respectively, the name of the file Perl is currently executing, and the Line number where it resides. These can be used in your own debugging statements, to remind yourself where your outputs were in the source code:
  print "On line " . __LINE__ . " of file " . __FILE__ . ", \$foo = $foo\n";
   
   
   
   
    

Note that neither of these markers are variables, so they cannot be interpolated in a double-quoted string

warn() & die()
These are the most basic of all debugging techniques. warn() takes a list of strings, and prints them to STDERR. If the last element of the list does not end in a newline, warn() will also print the current filename and line number on which the warning occurred. Execution then proceeds as normal.

die() is identical to warn(), with one major exception - the program exits after printing the list of strings.

All debugging statements should make use of either warn() or die() rather than print(). This will insure you see your debugging output even if STDOUT has been redirected, and will give you the helpful clues of exactly where in your code the warning occurred.

Antibugging in Perl 7 Tips for Reducing Complexity

"Complexity is the enemy, and our aim is to kill it." -Jan Baan

One of Perl's greatest strengths is its expressiveness and extreme conciseness. Complexity is the bane of software development: when a program grows beyond a certain size, it becomes much harder to test, maintain, read, or extend. Unfortunately, today's problems mean this is true for every program we need. Anything you can do to minimize the complexity of your program will pay handsome dividends.

The complexity of a program is a function of several factors:

Whenever a language allows you to change some code to reduce any of these factors, you reduce complexity.

Komodo 3.1 - Online Docs Debugging Perl Debugging Perl Remotely

When debugging a Perl program remotely, the program is executed on the remote system and the debug output is sent to Komodo. Komodo controls the debugging session (e.g. stepping and breakpoints) once the session starts on the remote system.

Perl remote debugging works on any system that can run the version of perl5db.pl distributed with Komodo. ActivePerl and most other distributions of Perl (version 5.6 or greater) will work.

Note: If you have the ActiveState Perl Development Kit (PDK) installed, follow the instructions for PDK users to disable the PDK debugger before continuing.

To debug Perl programs remotely:

Step One: Configure the Remote Machine

  1. Log in to the remote machine.

  2. Copy Komodo's perl debugger and its associated libraries to the remote machine by copying the entire dbgp/perllib sub-directory of the Komodo installation to the new machine, or download a package from the Komodo Remote Debugging page.

    Note: Do not copy perl5db.pl to the Perl "lib" directory on the remote machine, as this will overwrite the standard perl5db.pl file.

  3. On the remote machine, set the PERL5LIB environment variable to the location of the new perl5db.pl and its libraries. For example, if the remote machine is running Windows and perllib directory was copied to C:\misc\perllib, set the variable as follows:
    set PERL5LIB=C:\misc\perllib

    For example, if the remote machine is running Linux and perllib was copied to the /home/me/perl/komodo_perl_debugging directory, set the variable as follows:

    export PERL5LIB=/home/me/perl/komodo_perl_debugging/perllib
  4. On the remote machine, set the PERLDB_OPTS and DBGP_IDEKEY variables. This tells the Perl interpreter on the remote machine where to connect to Komodo or the DBGP Proxy and how to identify itself.
    	PERLDB_OPTS=RemotePort=<hostname>:<port>
    	DBGP_IDEKEY=<ide_key>
    • The port number must match the port number specified in Edit|Preferences|Debugger. Click Debug|Listener Status to check the current port.
    • Replace <hostname> with the name or IP address of the machine running Komodo.
    • If DBGP_IDEKEY is unset, the USER or USERNAME environment variable is used as the IDE Key.
    • The variable definitions must be on one line.

... ... ...

Interview 14 - Richard Foley

perlcast.com

Richard: Being able to interactively work with your code is a very powerful mechanism, really. Because, you can just experiment on the fly with all sort of constructs. You know, simple constructs, or things like when you're unsure about how somethings evaluates in a list context, or scalar context, or whether it is a list or scalar context. So you can just experiment and find out.

Josh: Okay, so on the subject of the book, you divided into three primary sections. The first being a general overview of the debugger, the second takes you through usage scenarios and customizing the debugger, and the final is a reference section. So, I was just wondering why you chose to layout the book in this way.

Richard: It seemed a fairly natural spread for me, I think, I was hoping that the book would be able to appeal to both people that hadn't really used the debugger before, hadn't really had much experience in, and therefore the first several chapters are completely oriented toward the beginner. If you are a more experienced Perl user and, quite possibly, already a debugger user, but you weren't sure of all the details, then that is where middle of the book was going to come more into effect, to get you up to speed there, really. And of course you need to have a reference, and every books have references, goodness me. The debugger command, well, there's quite lot of them really, especially the options. We needed to have some form of definitive reference of all the various command possibilities and the various syntaxes. Which, while they are multiplely intuitive, some of them can be a bit obscure, especially when you get down to the options. You need to have the absolutely right name in
some places. So, you sort of need to know where to look and that's where the online help, again, comes into hand there. In the debugger itself, there is a small screen, a help screen, that you can use. That you can bring up just with a simple "h" command at the prompt. And that gives you almost all the information you need to know at that point. To get more information, you would use "h" and then the command name itself.

Josh: You covered debugging modules and debugging objects separately in the book, and it seems like those two areas kind of overlap some in Perl because of the very loose object definitions. So, what is the difference when you're debugging those?

Richard: Essentially, a module is just a library. We've come to associate object oriented programming with little modules, but the two aren't strictly bound together in that way. I think treating a number of libraries as a debuggable entity is valid on its own, and there are things the debugger can help you with there. Equally when you use object oriented code it's entirely irrelevant whether you are actually using modules or you just got a whole bundle of code in a single file. You can still set up inheritance and member variables, classes and so on. And the debugger offers you certain commands to help you with your object oriented programming as well, like the "i" command, which just tells you a little bit about the inheritance of the object you're looking at. Or rather the executable statement you've got in front of you, but you would normally use it on an object.

Josh: Whenever I debug CGI scripts, typically I just print out to the screen and run them through the web browser, or something. So, you can actually debug [CGI scripts using, or] Perl CGI scripts, using the Perl debugger, but it does seem like it been a little bit tricky, if not impossible, honestly to me. So how would you go about doing that?

Richard: The debugger is a very useful tool when you are dealing with CGI scripts, just like any other Perl program. There's no particular magic there. You would just call your CGI script using "-d," where appropriate, at the end of the Perl path, and the debugger kicks in, takes control of the situation and offers you a prompt. The point where it gets tricky is if you are using Apache mod_perl, for example, where you are combining with a web server and you've got the debugger essentially already sitting inside, well Perl, already sitting inside C space, inside the web server. Even there, thanks to Doug MacEachern's work with the mod_perl code, Pierce provided a very simple interface which you can effectively switch on, and you can step inside mod_perl, as well. All you have to do is you have to get the server running in single user mode, and there's a small configuration file change you have to make in the Apache server config file. And then you can step through mod_perl programs, j
ust like you can step through any other Perl programs. So, it's very, very sweet, and very, very, simple. It's not complicated at all. The only complicated about it is trying it the first time. And once you have done that you think "Oh, it's so easy, why didn't I do this before." And that's the case over and over again I found that with the debugger. That people always where saying "isn't it complicated" or "isn't it strange," you know, and "how can you possibly do this and do that." And it basically just makes your live much, much easier and much more straightforward. It's a very powerful tool that people seem to miss because it's essentially unfamiliar.

I was at one job here in Germany where there were some people on a programming team here that spent, I think probably months of man-hours, well maybe weeks. They were trying to get a tracing mechanism in their moderately complicated Perl code, and they were using caller all the time to essentially step in all the time and print out stack traces during the runtime execution of their program. And all of this, of course, comes in standard with Perl. You can get stack traces, printing out all the arguments going into subroutines, what the return values are, just with a switch, with the "-t," inside the Perl debugger. It was an awful lot of work, which would have been completely saved had they bothered to read the documentation, you know. Which isn't to say that none of us ever don't like to reinvent every now and then, but that was an lot of work for absolutely nothing. It wasn't even as good, of course, as the debugger solution.

Josh: Whenever you say "reinventing the wheel," I am not sure if this is a reinvention or an improvement, or not, but there are some debugger replacements, or at least supplements, that are available, and one of these is "Devel-ebug." And how does this module actually compare to the Perl debugger?

Richard: I've not yet time to recall on this to dive into that a great deal. But I believe that's Leon's newer module, or at least I know he has been working on one. And I think any approach to making debugging Perl programs is a good thing. And if there's several debuggers out there to choose from that can only be a good thing too. There have been various attempts in the past, I think, to replace the debugger, because it is a little bit crusty. It essentially had a bit of a rewrite when Perl 5 came in, and since it has only been extended and extended and extended, and as you can imagine that led to very spaghetti like bundle of code to maintain, which can lead to its own problems. Essentially, any further development tools that we can get our hands on can only be a good thing.

Josh: Is there any GUI to sit on top of the debugger to maybe make it easier for beginning users to use that, other than the command line where you have to remember the commands?

Richard: Yeah, the classic one is probably coming from the UNIX background, is the ptkdb, the Perl/Tk Debugger interface, which works very well with all the Linux platforms. You just have Tk installed and you can run that. And that's a very mouse oriented debugger interface, and quite friendly. The other one, quite well known, is the Komodo debugger and Perl IDE from ActiveState, which, because I work mostly on UNIX and Linux I don't have actually much experience with. But from what I have seen of it it's very sweet. Any of the GUI interfaces that are available. Excellent particularly for CGI debugging. I mean, this is the case where with ptkdb, for example, you can set a display variable where you are using it. A neat little trick is the Perl code that's running by a web server will send a window to wherever set the display variable to, and you can debug from there. So you can debug from a completely remote machine.

Josh: In the book, you also show how to debug threaded applications and POE based applications. So, what kind of special support does the debugger have to make debugging these types of applications easier?

Richard: Where POE is concerned, really, there is all the extra support needed, because it's simply a single running application that's pretending to be threaded, or forked. So it works with that quite happily. Where you are using actual fork calls, and some program do, the debugger does support that. The only problem at hand is setting up a new console. And than you have to a little bit of higgery-pokery to get the correct console running, the correct xterm. The support for forked programs is moderately limited, but it is actually there. What we actually need is for some fork experts to come along, and to write all the various chunks of code to support the debugger on those platforms. The main problem at the moment really is that the Perl debugger is running inside what it thinks is an xterm, and it doesn't really know how to create more, because you need a new input and output for the debugger itself, not the program as such. There is some minimal support there for forks.

Where threads are concerned, that was a problem until quite recently, because all the variables inside the Perl debugger were being shared among all the threaded programs, and no one really knew which variable was in which thread. And that led to some quite interesting results. But that was fixed quite recently, 5.8.5 I think. And you can now use the Perl debugger with threads as well.

Josh: One feature of the debugger that looks really neat was the ability to debug regular expressions. But before we dive into that, a non-debugger related tip for working with regexes was to avoid contracting the "Leaning Toothpick Syndrome," and what is that, and how do I avoid it?

Richard: Right, Leaning Toothpick Syndrome is when you normally have a regexp, you normally start with a forward slash and then you end with a forward slash. And so, if you got any forward slash in your regex, like for example in a typical path name on a UNIX like system, it can get very confusing very quickly, which is the start slash and which is the end slash, and which is the slash in the middle, and has it been backslashed yet to escape it. If you just use different delimiters at the end, maybe a comment mark or open and close brackets or braces, that can make the regex a lot easier to read. And then you don't have to backslash your forward slashes any more, and you no longer get the Leaning Toothpick Syndrome. So when you just have so many forward slashes and backslashes to try to keep them in sync, it get very bitterly confusing.

Josh: Regular expression debugging seem to produce a lot of data, but then again regexes are almost miniature programs within your script. So, what types of information and controls does the debugger provide for regular expressions?

Richard: The debugger itself doesn't actually provide terribly much regex support itself. It uses what support there is in Perl already. Perl has its own regex engine, that will give you a lot of information if you ask it correctly. It seemed moderately relevant to include a chapter on this in the book, because there was so little information about it anywhere else, and people do have problems with their regexes. So it's nice to see one thing exploded. Essentially, you've got a couple of choices with regexes. You can use the re pragma, use regular expression module then or pragma (use re), which will show you what Perl is going to be doing, or show you what the regex engine is going to be doing in terms of compiling and optimizing your regex. Or you can use the debugging flags. You have to use -Dr for that. But for that you need to have a special Perl build with debugging support, which, agai
n, is not very complicated and shared to do that in the book. But its one more step you have to go through. But its quite nice to see your rexex actually exploded out, and walk through step by step.

Josh: When do I just use the print statement and when do I pull out the debugger? Is there something to look for, some kind of signals, to know that its time to actually invoke the debugger and get beyond the print?

Richard: If you don't turn around and just use it first off because its a convenient and a close friend, then yeah, you probably gonna be, maybe, at a stage where you are struggling with the print command. When you are saying something like "that just can't be right," and you are going round and round in circles, looking at data that is clearly not what you're expecting. And that really is a time when you should stop and say "Okay, I'm gonna step back and I'm just gonna force myself to go in there, to step inside the code, and to step through it and find out what the values of these variables actually are at the time, rather than assuming there are something of." And the debugger can help you do that. The nice thing about it is that it can do it without you actually altering your code in any way. One of the problems is, very often people will actually try to find a bug and help fix it. Finding it has involved, perhaps, change in the code in numerous place
s to put printstatements in, and then fixing it involves changing the code again and taking all that print statements out correctly, without affecting aversely, in any way, the running of the program. Sounds very straightforward, but I have seen a number of bugs appear just by people finding and fixing bugs actually introduce their own. And the debugger can help there, with just keeping you slightly arms-length. You are not changing the code in any way. You have complete control of what you are doing.

Josh: That was all the questions I had. Is there anything in the book that you think is really important that we should let people know about?

Richard: I think the last comment is a critical one: Don't change the source code. Don't change the code, just get in there and run your program and have a look around as it's running. It is a very powerful mechanism, and it's a very convenient mechanism. And it's a lot of fun as well.

Josh: Thank you. Well, the book is "Pro Perl Debugging." It's published by Apress, and is written by Richard Foley, who we've been talking to here on Perlcast. Richard, thank you very much for the interview.

Dr. Dobb's Web Site Code Coverage Analysis in Perl by Brian D Foy

ddj.com

Is all of your Perl code actually executing? Are some statements invoked as expected? The Devel::Coverage module can give you the answer, but you've got to ask the right questions.

Perl comes with a built-in debugging mechanism that allows you to create your own debugger or use one created by someone else. Perl coders can also use the Devel::Coverage debugging module to determine just how much of a program actually executes. This testing process is called coverage analysis. The Devel::Coverage module is available on the Comprehensive Perl Archive Network (CPAN). I'll show you how to use this sort of analysis to actually test all parts of your target program.

You use coverage analysis while testing your code (and everyone tests their code, right?) to ensure that you have done everything that necessary to exercise as much of the code as possible. Proper coverage analysis by itself does not make your code better or your programs bulletproof, but allows you to focus on problems in your code or in the test cases by examining different coverage metrics.

You can use several different coverage analysis

Recommended Links

Google matched content

Softpanorama Recommended

Top articles

[Nov 30, 2017] debugging - Perl Debugger Filehandle as Input Published on Nov 30, 2017 | stackoverflow.com

Sites

Video from Youtube

Tutorials

Cheat-sheets

Etc

Reference

NAME debug debugger - search.cpan.org

First of all, have you tried using the -w switch? If you're new to the Perl debugger, you may prefer to read perldebtut, which is a tutorial introduction to the debugger .

If you invoke Perl with the -d switch, your script runs under the Perl source debugger. This works like an interactive Perl environment, prompting for debugger commands that let you examine source code, set breakpoints, get stack backtraces, change the values of variables, etc. This is so convenient that you often fire up the debugger all by itself just to test out Perl constructs interactively to see what they do. For example:

    $ perl -d -e 42

In Perl, the debugger is not a separate program the way it usually is in the typical compiled environment. Instead, the -d flag tells the compiler to insert source information into the parse trees it's about to hand off to the interpreter. That means your code must first compile correctly for the debugger to work on it. Then when the interpreter starts up, it preloads a special Perl library file containing the debugger.

The program will halt right before the first run-time executable statement (but see below regarding compile-time statements) and ask you to enter a debugger command. Contrary to popular expectations, whenever the debugger halts and shows you a line of code, it always displays the line it's about to execute, rather than the one it has just executed.

Any command not recognized by the debugger is directly executed (eval'd) as Perl code in the current package. (The debugger uses the DB package for keeping its own state information.)

Note that the said eval is bound by an implicit scope. As a result any newly introduced lexical variable or any modified capture buffer content is lost after the eval. The debugger is a nice environment to learn Perl, but if you interactively experiment using material which should be in the same scope, stuff it in one line.

For any text entered at the debugger prompt, leading and trailing whitespace is first stripped before further processing. If a debugger command coincides with some function in your own program, merely precede the function with something that doesn't look like a debugger command, such as a leading ; or perhaps a +, or by wrapping it with parentheses or braces.

Debugger Commands

The debugger understands the following commands:

h
Prints out a summary help message
h [command]
Prints out a help message for the given debugger command.
h h
The special argument of h h produces the entire help page, which is quite long.

If the output of the h h command (or any command, for that matter) scrolls past your screen, precede the command with a leading pipe symbol so that it's run through your pager, as in

    DB> |h h

You may change the pager which is used via o pager=... command.

p expr
Same as print {$DB::OUT} expr in the current package. In particular, because this is just Perl's own print function, this means that nested data structures and objects are not dumped, unlike with the x command.

The DB::OUT filehandle is opened to /dev/tty, regardless of where STDOUT may be redirected to.

x [maxdepth] expr
Evaluates its expression in list context and dumps out the result in a pretty-printed fashion. Nested data structures are printed out recursively, unlike the real print function in Perl. When dumping hashes, you'll probably prefer 'x \%h' rather than 'x %h'. See Dumpvalue if you'd like to do this yourself.

The output format is governed by multiple options described under "Configurable Options".

If the maxdepth is included, it must be a numeral N; the value is dumped only N levels deep, as if the dumpDepth option had been temporarily set to N.

V [pkg [vars]]
Display all (or some) variables in package (defaulting to main) using a data pretty-printer (hashes show their keys and values so you see what's what, control characters are made printable, etc.). Make sure you don't put the type specifier (like $) there, just the symbol names, like this:
    V DB filename line

Use ~pattern and !pattern for positive and negative regexes.

This is similar to calling the x command on each applicable var.

X [vars]
Same as V currentpackage [vars].
y [level [vars]]
Display all (or some) lexical variables (mnemonic: mY variables) in the current scope or level scopes higher. You can limit the variables that you see with vars which works exactly as it does for the V and X commands. Requires the PadWalker module version 0.08 or higher; will warn if this isn't installed. Output is pretty-printed in the same style as for V and the format is controlled by the same options.
T
Produce a stack backtrace. See below for details on its output.
s [expr]
Single step. Executes until the beginning of another statement, descending into subroutine calls. If an expression is supplied that includes function calls, it too will be single-stepped.
n [expr]
Next. Executes over subroutine calls, until the beginning of the next statement. If an expression is supplied that includes function calls, those functions will be executed with stops before each statement.
r
Continue until the return from the current subroutine. Dump the return value if the PrintRet option is set (default).
<CR>
Repeat last n or s command.
c [line|sub]
Continue, optionally inserting a one-time-only breakpoint at the specified line or subroutine.
l
List next window of lines.
l min+incr
List incr+1 lines starting at min.
l min-max
List lines min through max. l - is synonymous to -.
l line
List a single line.
l subname
List first window of lines from subroutine. subname may be a variable that contains a code reference.
-
List previous window of lines.
v [line]
View a few lines of code around the current line.
.
Return the internal debugger pointer to the line last executed, and print out that line.
f filename
Switch to viewing a different file or eval statement. If filename is not a full pathname found in the values of %INC, it is considered a regex.

evaled strings (when accessible) are considered to be filenames: f (eval 7) and f eval 7\b access the body of the 7th evaled string (in the order of execution). The bodies of the currently executed eval and of evaled strings that define subroutines are saved and thus accessible.

/pattern/
Search forwards for pattern (a Perl regex); final / is optional. The search is case-insensitive by default.
?pattern?
Search backwards for pattern; final ? is optional. The search is case-insensitive by default.
L [abw]
List (default all) actions, breakpoints and watch expressions
S [[!]regex]
List subroutine names [not] matching the regex.
t
Toggle trace mode (see also the AutoTrace option).
t expr
Trace through execution of expr. See "Frame Listing Output Examples" in perldebguts for examples.
b
Sets breakpoint on current line
b [line] [condition]
Set a breakpoint before the given line. If a condition is specified, it's evaluated each time the statement is reached: a breakpoint is taken only if the condition is true. Breakpoints may only be set on lines that begin an executable statement. Conditions don't use if:
    b 237 $x > 30
    b 237 ++$count237 < 11
    b 33 /pattern/i
b subname [condition]
Set a breakpoint before the first line of the named subroutine. subname may be a variable containing a code reference (in this case condition is not supported).
b postpone subname [condition]
Set a breakpoint at first line of subroutine after it is compiled.
b load filename
Set a breakpoint before the first executed line of the filename, which should be a full pathname found amongst the %INC values.
b compile subname
Sets a breakpoint before the first statement executed after the specified subroutine is compiled.
B line
Delete a breakpoint from the specified line.
B *
Delete all installed breakpoints.
a [line] command
Set an action to be done before the line is executed. If line is omitted, set an action on the line about to be executed. The sequence of steps taken by the debugger is
  1. check for a breakpoint at this line
  2. print the line if necessary (tracing)
  3. do any actions associated with that line
  4. prompt user if at a breakpoint or in single-step
  5. evaluate line

For example, this will print out $foo every time line 53 is passed:

    a 53 print "DB FOUND $foo\n"
A line
Delete an action from the specified line.
A *
Delete all installed actions.
w expr
Add a global watch-expression. We hope you know what one of these is, because they're supposed to be obvious.
W expr
Delete watch-expression
W *
Delete all watch-expressions.
o
Display all options
o booloption ...
Set each listed Boolean option to the value 1.
o anyoption? ...
Print out the value of one or more options.
o option=value ...
Set the value of one or more options. If the value has internal whitespace, it should be quoted. For example, you could set o pager="less -MQeicsNfr" to call less with those specific options. You may use either single or double quotes, but if you do, you must escape any embedded instances of same sort of quote you began with, as well as any escaping any escapes that immediately precede that quote but which are not meant to escape the quote itself. In other words, you follow single-quoting rules irrespective of the quote; eg: o option='this isn\'t bad' or o option="She said, \"Isn't it?\"".

For historical reasons, the =value is optional, but defaults to 1 only where it is safe to do so--that is, mostly for Boolean options. It is always better to assign a specific value using =. The option can be abbreviated, but for clarity probably should not be. Several options can be set together. See "Configurable Options" for a list of these.

< ?
List out all pre-prompt Perl command actions.
< [ command ]
Set an action (Perl command) to happen before every debugger prompt. A multi-line command may be entered by backslashing the newlines.
< *
Delete all pre-prompt Perl command actions.
<< command
Add an action (Perl command) to happen before every debugger prompt. A multi-line command may be entered by backwhacking the newlines.
> ?
List out post-prompt Perl command actions.
> command
Set an action (Perl command) to happen after the prompt when you've just given a command to return to executing the script. A multi-line command may be entered by backslashing the newlines (we bet you couldn't've guessed this by now).
> *
Delete all post-prompt Perl command actions.
>> command
Adds an action (Perl command) to happen after the prompt when you've just given a command to return to executing the script. A multi-line command may be entered by backslashing the newlines.
{ ?
List out pre-prompt debugger commands.
{ [ command ]
Set an action (debugger command) to happen before every debugger prompt. A multi-line command may be entered in the customary fashion.

Because this command is in some senses new, a warning is issued if you appear to have accidentally entered a block instead. If that's what you mean to do, write it as with ;{ ... } or even do { ... }.

{ *
Delete all pre-prompt debugger commands.
{{ command
Add an action (debugger command) to happen before every debugger prompt. A multi-line command may be entered, if you can guess how: see above.
! number
Redo a previous command (defaults to the previous command).
! -number
Redo number'th previous command.
! pattern
Redo last command that started with pattern. See o recallCommand, too.
!! cmd
Run cmd in a subprocess (reads from DB::IN, writes to DB::OUT) See o shellBang, also. Note that the user's current shell (well, their $ENV{SHELL} variable) will be used, which can interfere with proper interpretation of exit status or signal and coredump information.
source file
Read and execute debugger commands from file. file may itself contain source commands.
H -number
Display last n commands. Only commands longer than one character are listed. If number is omitted, list them all.
q or ^D
Quit. ("quit" doesn't work for this, unless you've made an alias) This is the only supported way to exit the debugger, though typing exit twice might work.

Set the inhibit_exit option to 0 if you want to be able to step off the end the script. You may also need to set $finished to 0 if you want to step through global destruction.

R
Restart the debugger by exec()ing a new session. We try to maintain your history across this, but internal settings and command-line options may be lost.

The following setting are currently preserved: history, breakpoints, actions, debugger options, and the Perl command-line options -w, -I, and -e.

|dbcmd
Run the debugger command, piping DB::OUT into your current pager.
||dbcmd
Same as |dbcmd but DB::OUT is temporarily selected as well.
= [alias value]
Define a command alias, like
    = quit q

or list current aliases.

command
Execute command as a Perl statement. A trailing semicolon will be supplied. If the Perl statement would otherwise be confused for a Perl debugger, use a leading semicolon, too.
m expr
List which methods may be called on the result of the evaluated expression. The expression may evaluated to a reference to a blessed object, or to a package name.
M
Displays all loaded modules and their versions
man [manpage]
Despite its name, this calls your system's default documentation viewer on the given page, or on the viewer itself if manpage is omitted. If that viewer is man, the current Config information is used to invoke man using the proper MANPATH or -M manpath option. Failed lookups of the form XXX that match known manpages of the form perlXXX will be retried. This lets you type man debug or man op from the debugger.

On systems traditionally bereft of a usable man command, the debugger invokes perldoc. Occasionally this determination is incorrect due to recalcitrant vendors or rather more felicitously, to enterprising users. If you fall into either category, just manually set the $DB::doccmd variable to whatever viewer to view the Perl documentation on your system. This may be set in an rc file, or through direct assignment. We're still waiting for a working example of something along the lines of:

    $DB::doccmd = 'netscape -remote http://something.here/';

Configurable Options

The debugger has numerous options settable using the o command, either interactively or from the environment or an rc file. (./.perldb or ~/.perldb under Unix.)

recallCommand, ShellBang
The characters used to recall command or spawn shell. By default, both are set to !, which is unfortunate.
pager
Program to use for output of pager-piped commands (those beginning with a | character.) By default, $ENV{PAGER} will be used. Because the debugger uses your current terminal characteristics for bold and underlining, if the chosen pager does not pass escape sequences through unchanged, the output of some debugger commands will not be readable when sent through the pager.
tkRunning
Run Tk while prompting (with ReadLine).
signalLevel, warnLevel, dieLevel
Level of verbosity. By default, the debugger leaves your exceptions and warnings alone, because altering them can break correctly running programs. It will attempt to print a message when uncaught INT, BUS, or SEGV signals arrive. (But see the mention of signals in BUGS below.)

To disable this default safe mode, set these values to something higher than 0. At a level of 1, you get backtraces upon receiving any kind of warning (this is often annoying) or exception (this is often valuable). Unfortunately, the debugger cannot discern fatal exceptions from non-fatal ones. If dieLevel is even 1, then your non-fatal exceptions are also traced and unceremoniously altered if they came from eval'd strings or from any kind of eval within modules you're attempting to load. If dieLevel is 2, the debugger doesn't care where they came from: It usurps your exception handler and prints out a trace, then modifies all exceptions with its own embellishments. This may perhaps be useful for some tracing purposes, but tends to hopelessly destroy any program that takes its exception handling seriously.

AutoTrace
Trace mode (similar to t command, but can be put into PERLDB_OPTS).
LineInfo
File or pipe to print line number info to. If it is a pipe (say, |visual_perl_db), then a short message is used. This is the mechanism used to interact with a slave editor or visual debugger, such as the special vi or emacs hooks, or the ddd graphical debugger.
inhibit_exit
If 0, allows stepping off the end of the script.
PrintRet
Print return value after r command if set (default).
ornaments
Affects screen appearance of the command line (see Term::ReadLine). There is currently no way to disable these, which can render some output illegible on some displays, or with some pagers. This is considered a bug.
frame
Affects the printing of messages upon entry and exit from subroutines. If frame & 2 is false, messages are printed on entry only. (Printing on exit might be useful if interspersed with other messages.)

If frame & 4, arguments to functions are printed, plus context and caller info. If frame & 8, overloaded stringify and tied FETCH is enabled on the printed arguments. If frame & 16, the return value from the subroutine is printed.

The length at which the argument list is truncated is governed by the next option:

maxTraceLen
Length to truncate the argument list when the frame option's bit 4 is set.
windowSize
Change the size of code list window (default is 10 lines).

The following options affect what happens with V, X, and x commands:

arrayDepth, hashDepth
Print only first N elements ('' for all).
dumpDepth
Limit recursion depth to N levels when dumping structures. Negative values are interpreted as infinity. Default: infinity.
compactDump, veryCompact
Change the style of array and hash output. If compactDump, short array may be printed on one line.
globPrint
Whether to print contents of globs.
DumpDBFiles
Dump arrays holding debugged files.
DumpPackages
Dump symbol tables of packages.
DumpReused
Dump contents of "reused" addresses.
quote, HighBit, undefPrint
Change the style of string dump. The default value for quote is auto; one can enable double-quotish or single-quotish format by setting it to " or ', respectively. By default, characters with their high bit set are printed verbatim.
UsageOnly
Rudimentary per-package memory usage dump. Calculates total size of strings found in variables in the package. This does not include lexicals in a module's file scope, or lost in closures.

After the rc file is read, the debugger reads the $ENV{PERLDB_OPTS} environment variable and parses this as the remainder of a "O ..." line as one might enter at the debugger prompt. You may place the initialization options TTY, noTTY, ReadLine, and NonStop there.

If your rc file contains:

  parse_options("NonStop=1 LineInfo=db.out AutoTrace");

then your script will run without human intervention, putting trace information into the file db.out. (If you interrupt it, you'd better reset LineInfo to /dev/tty if you expect to see anything.)

TTY
The TTY to use for debugging I/O.
noTTY
If set, the debugger goes into NonStop mode and will not connect to a TTY. If interrupted (or if control goes to the debugger via explicit setting of $DB::signal or $DB::single from the Perl script), it connects to a TTY specified in the TTY option at startup, or to a tty found at runtime using the Term::Rendezvous module of your choice.

This module should implement a method named new that returns an object with two methods: IN and OUT. These should return filehandles to use for debugging input and output correspondingly. The new method should inspect an argument containing the value of $ENV{PERLDB_NOTTY} at startup, or "$ENV{HOME}/.perldbtty$$" otherwise. This file is not inspected for proper ownership, so security hazards are theoretically possible.

ReadLine
If false, readline support in the debugger is disabled in order to debug applications that themselves use ReadLine.
NonStop
If set, the debugger goes into non-interactive mode until interrupted, or programmatically by setting $DB::signal or $DB::single.

Here's an example of using the $ENV{PERLDB_OPTS} variable:

    $ PERLDB_OPTS="NonStop frame=2" perl -d myprogram

That will run the script myprogram without human intervention, printing out the call tree with entry and exit points. Note that NonStop=1 frame=2 is equivalent to N f=2, and that originally, options could be uniquely abbreviated by the first letter (modulo the Dump* options). It is nevertheless recommended that you always spell them out in full for legibility and future compatibility.

Other examples include

    $ PERLDB_OPTS="NonStop LineInfo=listing frame=2" perl -d myprogram

which runs script non-interactively, printing info on each entry into a subroutine and each executed line into the file named listing. (If you interrupt it, you would better reset LineInfo to something "interactive"!)

Other examples include (using standard shell syntax to show environment variable settings):

  $ ( PERLDB_OPTS="NonStop frame=1 AutoTrace LineInfo=tperl.out"
      perl -d myprogram )

which may be useful for debugging a program that uses Term::ReadLine itself. Do not forget to detach your shell from the TTY in the window that corresponds to /dev/ttyXX, say, by issuing a command like

  $ sleep 1000000

See "Debugger Internals" in perldebguts for details.

Debugger input/output

Prompt
The debugger prompt is something like
    DB<8>

or even

    DB<<17>>

where that number is the command number, and which you'd use to access with the built-in csh-like history mechanism. For example, !17 would repeat command number 17. The depth of the angle brackets indicates the nesting depth of the debugger. You could get more than one set of brackets, for example, if you'd already at a breakpoint and then printed the result of a function call that itself has a breakpoint, or you step into an expression via s/n/t expression command.

Multiline commands
If you want to enter a multi-line command, such as a subroutine definition with several statements or a format, escape the newline that would normally end the debugger command with a backslash. Here's an example:
      DB<1> for (1..4) {         \
      cont:     print "ok\n";   \
      cont: }
      ok
      ok
      ok
      ok

Note that this business of escaping a newline is specific to interactive commands typed into the debugger.

Stack backtrace
Here's an example of what a stack backtrace via T command might look like:
    $ = main::infested called from file `Ambulation.pm' line 10
    @ = Ambulation::legs(1, 2, 3, 4) called from file `camel_flea' line 7
    $ = main::pests('bactrian', 4) called from file `camel_flea' line 4

The left-hand character up there indicates the context in which the function was called, with $ and @ meaning scalar or list contexts respectively, and . meaning void context (which is actually a sort of scalar context). The display above says that you were in the function main::infested when you ran the stack dump, and that it was called in scalar context from line 10 of the file Ambulation.pm, but without any arguments at all, meaning it was called as &infested. The next stack frame shows that the function Ambulation::legs was called in list context from the camel_flea file with four arguments. The last stack frame shows that main::pests was called in scalar context, also from camel_flea, but from line 4.

If you execute the T command from inside an active use statement, the backtrace will contain both a require frame and an eval) frame.

Line Listing Format
This shows the sorts of output the l command can produce:
    DB<<13>> l
  101:                @i{@i} = ();
  102:b               @isa{@i,$pack} = ()
  103                     if(exists $i{$prevpack} || exists $isa{$pack});
  104             }
  105
  106             next
  107==>              if(exists $isa{$pack});
  108
  109:a           if ($extra-- > 0) {
  110:                %isa = ($pack,1);

Breakable lines are marked with :. Lines with breakpoints are marked by b and those with actions by a. The line that's about to be executed is marked by ==>.

Please be aware that code in debugger listings may not look the same as your original source code. Line directives and external source filters can alter the code before Perl sees it, causing code to move from its original positions or take on entirely different forms.

Frame listing
When the frame option is set, the debugger would print entered (and optionally exited) subroutines in different styles. See perldebguts for incredibly long examples of these.

Debugging compile-time statements

If you have compile-time executable statements (such as code within BEGIN and CHECK blocks or use statements), these will not be stopped by debugger, although requires and INIT blocks will, and compile-time statements can be traced with AutoTrace option set in PERLDB_OPTS). From your own Perl code, however, you can transfer control back to the debugger using the following statement, which is harmless if the debugger is not running:

    $DB::single = 1;

If you set $DB::single to 2, it's equivalent to having just typed the n command, whereas a value of 1 means the s command. The $DB::trace variable should be set to 1 to simulate having typed the t command.

Another way to debug compile-time code is to start the debugger, set a breakpoint on the load of some module:

    DB<7> b load f:/perllib/lib/Carp.pm
  Will stop on load of `f:/perllib/lib/Carp.pm'.

and then restart the debugger using the R command (if possible). One can use b compile subname for the same purpose.

Debugger Customization

The debugger probably contains enough configuration hooks that you won't ever have to modify it yourself. You may change the behaviour of debugger from within the debugger using its o command, from the command line via the PERLDB_OPTS environment variable, and from customization files.

You can do some customization by setting up a .perldb file, which contains initialization code. For instance, you could make aliases like these (the last one is one people expect to be there):

    $DB::alias{'len'}  = 's/^len(.*)/p length($1)/';
    $DB::alias{'stop'} = 's/^stop (at|in)/b/';
    $DB::alias{'ps'}   = 's/^ps\b/p scalar /';
    $DB::alias{'quit'} = 's/^quit(\s*)/exit/';

You can change options from .perldb by using calls like this one;

    parse_options("NonStop=1 LineInfo=db.out AutoTrace=1 frame=2");

The code is executed in the package DB. Note that .perldb is processed before processing PERLDB_OPTS. If .perldb defines the subroutine afterinit, that function is called after debugger initialization ends. .perldb may be contained in the current directory, or in the home directory. Because this file is sourced in by Perl and may contain arbitrary commands, for security reasons, it must be owned by the superuser or the current user, and writable by no one but its owner.

You can mock TTY input to debugger by adding arbitrary commands to @DB::typeahead. For example, your .perldb file might contain:

    sub afterinit { push @DB::typeahead, "b 4", "b 6"; }

Which would attempt to set breakpoints on lines 4 and 6 immediately after debugger initialization. Note that @DB::typeahead is not a supported interface and is subject to change in future releases.

If you want to modify the debugger, copy perl5db.pl from the Perl library to another name and hack it to your heart's content. You'll then want to set your PERL5DB environment variable to say something like this:

    BEGIN { require "myperl5db.pl" }

As a last resort, you could also use PERL5DB to customize the debugger by directly setting internal variables or calling debugger functions.

Note that any variables and functions that are not documented in this document (or in perldebguts) are considered for internal use only, and as such are subject to change without notice.

Readline Support

As shipped, the only command-line history supplied is a simplistic one that checks for leading exclamation points. However, if you install the Term::ReadKey and Term::ReadLine modules from CPAN, you will have full editing capabilities much like GNU readline(3) provides. Look for these in the modules/by-module/Term directory on CPAN. These do not support normal vi command-line editing, however.

A rudimentary command-line completion is also available. Unfortunately, the names of lexical variables are not available for completion.

Editor Support for Debugging

If you have the FSF's version of emacs installed on your system, it can interact with the Perl debugger to provide an integrated software development environment reminiscent of its interactions with C debuggers.

Perl comes with a start file for making emacs act like a syntax-directed editor that understands (some of) Perl's syntax. Look in the emacs directory of the Perl source distribution.

A similar setup by Tom Christiansen for interacting with any vendor-shipped vi and the X11 window system is also available. This works similarly to the integrated multiwindow support that emacs provides, where the debugger drives the editor. At the time of this writing, however, that tool's eventual location in the Perl distribution was uncertain.

Users of vi should also look into vim and gvim, the mousey and windy version, for coloring of Perl keywords.

Note that only perl can truly parse Perl, so all such CASE tools fall somewhat short of the mark, especially if you don't program your Perl as a C programmer might.

The Perl Profiler

If you wish to supply an alternative debugger for Perl to run, just invoke your script with a colon and a package argument given to the -d flag. The most popular alternative debuggers for Perl is the Perl profiler. Devel::DProf is now included with the standard Perl distribution. To profile your Perl program in the file mycode.pl, just type:

    $ perl -d:DProf mycode.pl

When the script terminates the profiler will dump the profile information to a file called tmon.out. A tool like dprofpp, also supplied with the standard Perl distribution, can be used to interpret the information in that profile.

Debugging regular expressions

See also Rx, the Perl Regular Expression Debugger

use re 'debug' enables you to see the gory details of how the Perl regular expression engine works. In order to understand this typically voluminous output, one must not only have some idea about how regular expression matching works in general, but also know how Perl's regular expressions are internally compiled into an automaton. These matters are explored in some detail in "Debugging regular expressions" in perldebguts.

Debugging memory usage

Perl contains internal support for reporting its own memory usage, but this is a fairly advanced concept that requires some understanding of how memory allocation works. See "Debugging Perl memory usage" in perldebguts for the details.

You did try the -w switch, didn't you?

perldebtut, perldebguts, re, DB, Devel::DProf, dprofpp, Dumpvalue, and perlrun.

When debugging a script that uses #! and is thus normally found in $PATH, the -S option causes perl to search $PATH for it, so you don't have to type the path or which $scriptname.

  $ perl -Sd foo.pl

Symbolic Debugging

A symbolic debugger is an extremely useful tool. Trying to develop code without using one is a seriously strange thing to do. A symbolic debugger controls the operation of a running program and is able to show the correspondence between the bit of code the CPU is about to execute and the lines of source code from which that code was compiled. In short, learn how to use a debugger. There is not one single "all singing, all dancing" debugger out there; you may have to learn to work with a couple of different ones, especially if you find yourself working in a variety of different languages. On UNIX-like systems either dbx or gdb (or both) should be available to debug compiled code. I prefer using gdb if it's available (it's the standard debugger on all Linux distributions). The perl interpreter has a built-in debugger. You saw a hint of that before when we traced a perl script. ROOT macros can be debugged using the built-in debugging capabilities of the CINT interpreter.

Most debuggers have a large collection of confusing commands for controlling and examining a running program. The good news is that for most purposes you really only need to learn a few commands and concepts.

  1. breakpoints
  2. run
  3. continue
  4. conditional breakpoints
  5. step
  6. step into
  7. examining variables


Etc

Society

Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

Quotes

War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

Bulletin:

Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

History:

Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D


Copyright © 1996-2021 by Softpanorama Society. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to to buy a cup of coffee for authors of this site

Disclaimer:

The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the Softpanorama society. We do not warrant the correctness of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Last updated: December 30, 2020