Pro Perl Debugging 1st Edition Richard Foley Instant Download
Pro Perl Debugging 1st Edition Richard Foley Instant Download
download
https://ebookname.com/product/pro-perl-debugging-1st-edition-
richard-foley/
Get the full ebook with Bonus Features for a Better Reading Experience on ebookname.com
Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...
https://ebookname.com/product/web-graphics-perl-tk-best-of-the-
perl-journal-1st-edition-jon-orwant-ph-d/
https://ebookname.com/product/learning-perl-5th-edition-randal-
schwartz/
https://ebookname.com/product/extending-and-embedding-perl-tim-
jenness/
https://ebookname.com/product/creatio-ex-nihilo-and-the-theology-
of-st-augustine-1st-new-ed-edition-n-joseph-torchia/
Developing Student Graduateness and Employability
Issues Provocations Theory and Practical Guidelines 1st
Edition Melinde Coetzee
https://ebookname.com/product/developing-student-graduateness-
and-employability-issues-provocations-theory-and-practical-
guidelines-1st-edition-melinde-coetzee/
https://ebookname.com/product/iain-sinclair-salt-studies-in-
contemporary-literature-culture-1st-ed-edition-robert-bond/
https://ebookname.com/product/practical-reasoning-and-ethical-
decision-1st-edition-robert-audi/
https://ebookname.com/product/black-masculinity-and-sexual-
politics-routledge-research-in-race-and-ethnicity-1st-edition-
anthony-j-lemelle-jr/
https://ebookname.com/product/vietnam-and-the-west-2nd-edition-
giambattista-vico/
Kashmir Insurgency and After 3rd Edition Balraj Puri
https://ebookname.com/product/kashmir-insurgency-and-after-3rd-
edition-balraj-puri/
Pro Perl Debugging
From Professional to Expert
RICHARD FOLEY WITH ANDY LESTER
Pro Perl Debugging: From Professional to Expert
Copyright © 2005 by Richard Foley with Andy Lester
Lead Editor: Jason Gilmore
Technical Reviewer: Andy Lester
Editorial Board: Steve Anglin, Dan Appleman, Ewan Buckingham, Gary Cornell, Tony Davis, Jason Gilmore,
Jonathan Hassell, Chris Mills, Dominic Shakeshaft, Jim Sumser
Associate Publisher: Grace Wong
Project Manager: Emily K. Wolman
Copy Edit Manager: Nicole LeClerc
Copy Editor: Julie Smith
Production Manager: Kari Brooks-Copony
Production Editor: Linda Marousek
Compositor and Artist: Kinetic Publishing Services, LLC
Proofreader: Sue Boshers
Indexer: Rebecca Plunkett
Cover Designer: Kurt Krames
Manufacturing Manager: Tom Debolski
Library of Congress Cataloging-in-Publication Data
Foley, Richard.
Pro Perl debugging : from professional to expert / Richard Foley with
Andy Lester.
p. cm.
Includes bibliographical references and index.
ISBN 1-59059-454-1 (alk. paper)
1. Perl (Computer program language) 2. Debugging in computer science.
I. Lester, Andy. II. Title.
QA76.73.P22F62 2005
005.13′3—dc22
2005016006
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means,
electronic or mechanical, including photocopying, recording, or by any information storage or retrieval
system, without the prior written permission of the copyright owner and the publisher.
ISBN: 1-59059-454-1
Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1
Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrence
of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark
owner, with no intention of infringement of the trademark.
Distributed to the book trade in the United States by Springer-Verlag New York, Inc., 233 Spring Street, 6th
Floor, New York, NY 10013, and outside the United States by Springer-Verlag GmbH & Co. KG, Tiergartenstr. 17,
69112 Heidelberg, Germany.
In the United States: phone 1-800-SPRINGER, fax 201-348-4505, e-mail orders@springer-ny.com, or visit
http://www.springer-ny.com. Outside the United States: fax +49 6221 345229, e-mail orders@springer.de,
or visit http://www.springer.de.
For information on translations, please contact Apress directly at 2560 Ninth Street, Suite 219, Berkeley,
CA 94710. Phone 510-549-5930, fax 510-549-5939, e-mail info@apress.com, or visit http://www.apress.com.
The information in this book is distributed on an “as is” basis, without warranty. Although every precau-
tion has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liabil-
ity to any person or entity with respect to any loss or damage caused or alleged to be caused directly or
indirectly by the information contained in this work.
The source code for this book is available to readers at http://www.apress.com in the Downloads section.
You will need to answer questions pertaining to this book in order to successfully download the code.
I’d like to dedicate this book to my wife, Joy, and to my daughters, Catherine and Jennifer.
Without them it would all seem rather pointless—even if they do call me an angeber
(show-off) while pointing to daddy’s name as the actual author of a programming book.
And to Spot, for being a friend for 15 years.
—Richard
For Amy and Quinn, the two girls who make me laugh the most.
—Andy
Contents at a Glance
CHAPTER 1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
CHAPTER 2 Inspecting Variables and Getting Help . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
CHAPTER 3 Controlling Program Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
CHAPTER 4 Debugging a Simple Command Line Program . . . . . . . . . . . . . . . . . . . 39
CHAPTER 5 Tracing Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
CHAPTER 6 Debugging Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
CHAPTER 7 Debugging Object-Oriented Perl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
CHAPTER 8 Using the Debugger As a Shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
CHAPTER 9 Debugging a CGI Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
CHAPTER 10 Perl Threads and Forked Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
CHAPTER 11 Debugging Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
CHAPTER 12 Debugger Customization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
CHAPTER 13 Optimization and Performance Hints and Tips . . . . . . . . . . . . . . . . . 211
CHAPTER 14 Command Line and GUI Debuggers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
CHAPTER 15 Comprehensive Command Reference. . . . . . . . . . . . . . . . . . . . . . . . . . 239
CHAPTER 16 Book References and URLs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
v
Contents
■CHAPTER 1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
What Is It? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Down the Rabbit Hole . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Why Should You Use the Perl Debugger? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Using the Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Book Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Section 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Section 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Section 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Technical Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Development. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
vii
viii ■CONTENTS
findvars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
An Example Run. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
The Mission . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Running findvars Under the Debugger . . . . . . . . . . . . . . . . . . . . . . . . . 42
Checking the Input. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Comparing Before and After. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Examining Internal Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Looping Through %INC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Error Handling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Checking Progress . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Setting a Breakpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Inspecting the Contents of a Loaded Library File . . . . . . . . . . . . . . . . 51
Setting an Action . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Inspecting the Arguments to a Subroutine . . . . . . . . . . . . . . . . . . . . . 54
Consulting the Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Exploring Restart Possibilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Modifying the Code Harmlessly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Storing Our Command History and Restarting the Debugger. . . . . . 57
Rerunning Earlier Debugger Commands . . . . . . . . . . . . . . . . . . . . . . . 58
Checking Your Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Fixing the Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
■INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
About the Authors
■ANDY LESTER (http://petdance.com) has been a professional programmer for nineteen years
and a Perl evangelist for a decade. As one of the core Perl developers, Andy’s interests are focused
on quality assurance—he maintains eight testing modules on the CPAN, as well as the Perl QA
website (http://qa.perl.org).
Andy is a frequent speaker at the O’Reilly Open Source Convention, YAPC, and at Perl
Monger meetings around the country. He’s spoken around the United States on a variety of
programming topics including automated testing, Perl security, web agent automation,
project management, and effective job searching for programmers.
Andy has written or edited for a dozen books. Three of the articles on his popular
WWW::Mechanize module are included in O’Reilly’s “Spidering Hacks.” Andy has also
written articles for every single Perl magazine published in the United States (both of
them).
By day, Andy manages a crack squad of web programmers for Follett Library Resources
(http://www.titlewave.com) in McHenry, Illinois. He lives with his wife, Amy; daughter,
Quinn; and Baxter, the world’s neediest dog.
xv
Acknowledgments
F irst, I’d like to thank Larry Wall for the Perl programming language—it’s just so much fun
to use. Also, thanks are due to the many people who took his original debugger and made it
into the complex and functional beast that it is now. I’d particularly like to thank Gabor Szabo
for his part in getting this project off the ground, and Joe McMahon for his advice and support
during the writing phase. Many thanks to Andy Lester for agreeing to help get the book finished
when time was of the essence, and for at least doubling his work load in one fell swoop. Thanks
to Emily Wolman for retaining belief in the book through a long and protracted cat-herding
exercise. Many thanks to Jason Gilmore for being the third and most stalwart of editors, his
many suggestions and lively presence keeping the book on track as well as helping to form
its content into a coherent whole. Thanks also to the many unseen people in the actual pro-
duction phase who are essential to the process of creating the final book you are now holding,
including our erstwhile copy editor Julie Smith, and Linda Marousek, who was responsible for
its production. Finally, if there remain any errors or omissions, these are of course my sole
responsibility.
—Richard
xvii
Introduction
E ver since computers were invented, and every day since then, bugs have been found in
program code. Although the use of the term “bug” to refer to a problem predates computers,
it was defined in our context when Lady Lovelace squashed a moth that was interfering with
the clean operation of a valve in the early computer she was developing. From big bugs that
crash the operating system of a single PC, to little bugs that send a space probe millions of
miles past its intended destination, these things will always be with us. Because programmers
will always be human we must learn how to recognize a bug in the first place, to identify the
location of the bug, and finally to safely remove it from the code
The ability to efficiently debug code is a necessary part of any competent programmer’s
skill set. The code may belong to a body of work produced by the programmer herself, or adopted
in a maintainance role from a predecessor. Whatever the case, debugging succesfully appears
at times to be a black art. Some people can do it very well indeed, and others just never really
get to grips with it at all. While a methodical approach is required to identify the precise loca-
tion of any bug, using sensible tools can make the task much easier, and much faster, to com-
plete. When programming using Perl, the tool of choice will be the Perl debugger, supplied with
every Perl distribution since the first one.
This book is an in-depth tutorial and reference for the Perl debugger, perhaps the most
powerful debugging tool available for Perl programs today. It was written with two groups in
mind. The first is the large number of Perl programmers who don’t know that a debugger for
Perl even exists. The second group is the Perl programmers out there who shy away from using
the debugger because it’s a new, and apparently complex, animal.
Our aim is to demonstrate the debugger in the many real-world environments the pro-
fessional programmer will actually work with. We cover everything from the inspection and
modification of Perl code on-the-fly at run time and compile time without changing the source
on disk; to tracing and breaking program execution selectively. You’ll learn to debug multiple
library object-oriented modules, including both in-house code and code written by a third
party, to step through both a standard CGI program and a mod_perl-enabled apache handler
from within the web server (but at the Perl level), and to debug multi-tasking Perl programs
using both fork and threads.
By the time you finish this book, you will be able to make informed decisions for when
to use the humble print statement or the powerful Perl debugger to help you in your quest to
search and destroy those troublesome, ever-present gremlins of the programming world. You
will know how to use the debugger as a Perl shell to experiment with different code constructs,
in advance of typing them into a system file for later execution. You will no longer be constrained
by the unsteady feeling of not knowing, or repelled by the fear of the unfamiliar. By the final
chapter you will be able to revel in the ability to use a powerful investigative and exploratory
tool, should you wish to use it, which is always at your fingertips. Above all, you will have a
choice.
xix
CHAPTER 1
■■■
Introduction
Mars attacks!
M ention the Perl debugger to the average Perl programmer, and you often receive a strange
contorted grimace in response, and a spluttered, “I always use the print statement!,” as they
retreat down the corridor, waving incense in the air, looking as if they’re being chased by aliens.
In fact, similar behavior seems to apply to nearly all programmers when they’re approached with
a matter known to elicit debate in the programming community. After all, most would acknowl-
edge that programmers can often be divided into many factions—for instance, those who use
object-oriented methods or procedural functions (but not both), those who always use modules
and those who never do, those who prefer vi and those who worship emacs. In the same fashion,
it seems as though we can also classify two other species of programmers on the planet, those
who use a debugger and those who are unable to.
We hope that by the end of this book, the truth will emerge . . . that there are in fact many
Perl programmers on this planet; all of whom use the print statement, all of whom can also use
the debugger, if they so choose, and that the world will be a better place for having the choice.
What Is It?
The Perl debugger is an extremely useful tool for troubleshooting your Perl applications. It can
help you locate, identify, and then fix the problems in your code, whether you’ve written it your-
self or have inherited it in some manner.
This book won’t be the panacea to all of your programming problems, but it will give you the
capability to use a tool which can help you bugfix your applications, quickly and with confidence.
After reading this book, you will be able to find all those elusive bugs, and be able to do so with
absolute precision.
You could, of course, follow the lead of many lost programmers we’ve seen, and just cruise
about aimlessly looking at various bits of code, scattering ever more desperate print statements
around, in the often forlorn hope that one might fall over the problem, more or less accidentally.
This is the kind of approach that could also be described as the programming equivalent of
trench warfare, where the damage inflicted on our side is presumed to be an unavoidable side
effect of the main aim or purpose.
When you change the source code of a program in pursuit of the bug, you should know that
you have other options. Changing code is often regarded as inevitable by people without the
knowledge to do otherwise. Do not make the simple mistake of confusing finding the bug with
fixing the bug. Otherwise you are just as likely to unwittingly create a new one.
1
2 CHAPTER 1 ■ INTRODUCTION
Perhaps the most important benefit of using the Perl debugger is the capability to use it to
pinpoint a problem quickly, and most importantly, without touching or altering the source code
in any way. The entire behavior of the running Perl program, both at compiletime and at runtime,
can be inspected, paused, restarted, and entirely modified, at will, without changing one single
bit of code. In the greater scheme of things, this simple and critical fact is usually overlooked.
■Note For those who do not know, a breakpoint is a point in the program code where the debugger will
stop execution during runtime, thus enabling the programmer to inspect or change the value of variables,
objects or code. The call stack is the sequence of subroutines which have been called from the outermost, or
main(), context to the current innermost subroutine. When tracing a program, the information given with the
call stack may be expanded to include subroutine arguments.
It might seem daft at first sight, especially to traditionally trained programmers, that a pro-
grammer would not know this information. But partly because Perl is such a good and intuitive
language to learn, there are, in fact, many experienced Perl programmers working today who
do not know how to use a debugger, and are missing out on the power that has always been at
their fingertips. Indeed, the debugger has been available in every release of Perl since version 1.
I hope and expect that as you work through this book, you’ll meet many familiar friends and
concepts, and you’ll see that the rabbit hole really isn’t that strange after all.
In the final analysis, the real reasons for not using the debugger are perhaps a lot less numer-
ous and may be reasonably reduced to the following short list:
While these comments are perfectly reasonable, and are in fact related to one another, we
hope this book will resolve both these cases, and enable you to use the debugger for what it’s
best at: helping you to find and squash bugs. This is not to say that using the Perl debugger, or
indeed any debugger, is necessarily easy or simple. Like using any good tool, it takes time and
effort to become technically proficient and useful with it.
This will be time well spent.
4 CHAPTER 1 ■ INTRODUCTION
> perl -d -e 0
Loading DB routines from perl5db.pl version 1.27 Editor support available.
Enter h or 'h h' for help, or 'man perldebug' for more help.
main::(-e:1): 0
DB<1> print "Hello World\n"
Hello World
DB<2> q
>
In all cases throughout the book, you are encouraged to try the examples offered. You cannot
damage your program from within the debugger, as it is within a runtime context. As a certain
well-known advert once said, “Let your fingers do the walking!”
Book Layout
This book consists of 16 chapters, and is intended to foster a progressive learning experience,
with many of the chapters building on material appearing earlier in the book. In this section
we’ll summarize the chapter content.
Section 1
The first section introduces the Perl debugger to the programmer who has not used the debug-
ger before. Here, we discuss what the debugger is, what to call it, and the basic commands avail-
able. Programmers who already use other debuggers on a regular basis, may wish to skim this
section.
• Chapter 1 offers a general introduction to the debugger as a topic, and shows you how to
invoke the debugger, execute a command, and exit.
• Chapter 3 takes you through the most essential commands for competent debugging:
including setting breakpoints, enabling variable watches, setting action commands, and
inspecting variables.
• Chapter 4 walks you through the actual debugging of a short command line program, and
gives you a feel for how this all works on a real-life problem.
Section 2
The second and central section takes up the bulk of the book, and shows you how to use the debug-
ger in a number of both common and unusual situations. This section deals with all the commands
of the standard Perl debugger and, as your skill level increases, how to customize it to build your
own version of the debugger.
CHAPTER 1 ■ INTRODUCTION 5
• Chapter 5 explores tracing program execution, and functionality that is settable per
line, per block, per file, globally, or on-the-fly by command.
• Chapter 6 demonstrates debugging a program that uses several libraries or modules, and
certain special breakpoint commands which are designed specifically with this in mind.
• Chapter 8 looks at the debugger as a Perl shell, and is a place to experiment with Perl
programming constructs.
• Chapter 10 shows how the debugger supports working with forked and multi-threaded
Perl programs, and how it is possible to follow the multiple STDIN, STDOUT, STDERR
and debugger filehandles in those processes.
• Chapter 12 covers customizing the debugger, and how to change its behavior to suit your
particular environment or requirements.
Section 3
The third and final section is essentially a reference section including advanced optimization
suggestions, such as a list of every debugger command, variable, option, book, perldoc, and book
reference.
• Chapter 13 offers optimization as well as performance hints and tips for working with Perl.
It includes examples from some of the many development-oriented modules that are
available either via the CPAN or that come with the standard distribution.
• Chapter 14 compares the standard command line debugger and the various GUI alter-
natives available from different sources, some open source, some proprietary.
• Chapter 15 is a comprehensive command reference for all the available commands and
options available in the standard debugger.
• Chapter 16 is a list of useful perldoc, book, and URL references. Here, you can get more
information on both the Perl debugger, and the general topic of debugging itself.
Technical Notes
For all the examples in this book we use the 1.27 version of the debugger, distributed with the
current, stable version of Perl v5.8.5. We mostly use the command line debugger, which comes
with Perl and should work on all systems as long as Perl is installed. There are also a number of
GUI (Graphical User Interface) options, which are explored in Chapter 14.
The environment in which we demonstrate our command line examples is the bash shell on
Linux. While all examples should run equally well on all variants of Unix, there may be some
lack of support for Windows and Macintosh users in certain cases. Generally speaking the
6 CHAPTER 1 ■ INTRODUCTION
debugger behaves equally well in all cases, but the system calls and file commands are distinctly
operating system specific. For example, when executing a one-line Perl program via the -e
command, you may use single quotes on Linux, like this:
Whereas on Windows, you may be forced to use double quotes, like this:
■Note In the examples throughout this book we use perl to call the Perl interpreter, even when it may
have been installed under your system under a different name or a different path.
Development
Perl has seen continual development since version 1. Indeed every version of Perl has had a debug-
ger as part of the toolkit, and it can only be expected that the debugger would also develop. In
this book therefore, we track the major differences between debugger versions since Perl v5.0053,
(see Chapter 15), to make it as useful for as many people as possible. Many people have con-
tributed large and small patches, and in particular the following people (see Table 1-2) deserve
special mention for their contributions to debugger development to date.
Summary
By the conclusion of this introductory chapter, you should have a good overview of the Perl debug-
ger itself, and of how this book will approach the subject of debugging Perl programs. You should
be able to start the debugger, execute some Perl code or a debugger command, and quit the
debugger and return to your operating system environment.
The next chapter will discuss the most commonly used commands for inspecting the envi-
ronment of your program, and how to list the code and inspect the runtime variables within it.
We also find out how to use the built-in help facility to get more information for a particular
command from both the debugger and the system itself.
CHAPTER 2
■■■
I n this chapter you’ll familiarize yourself with the basic command line debugger interface, learn
how to inspect the data of your running program, and explore your environment. Instead of
using your infallible intuition, like Clousseau, you will use the tools at your disposal to determine
what variables are available to you at any given moment throughout a programs execution.
You’ll also learn how to examine code in a file loaded elsewhere in Perl space, for example
an entry in the %INC hash, which is the list of loaded modules, as well as how to retrieve a list of
subroutines or methods available for a particular class or object. Not content to stop there, you’ll
also learn how to find the help and manual pages, and take advantage of the command history
mechanism.
Note that you won’t do any actual debugging in this chapter—we are solely concerned with
helping you to become familiar with the debugging environment and to determine what infor-
mation the debugger makes available to you.
However, to enter the debugger just to get a feel for how it works, or to experiment with
a code construct, for example, you’ll also need to include the -e runtime switch, which tells the
debugger to expect a Perl expression on the command line. The expression doesn’t need to be
complicated—in our first example a simple zero will suffice:
%> perl -d -e 0
Loading DB routines from perl5db.pl version 1.27
Editor support available.
7
8 CHAPTER 2 ■ INSPECTING VARIABLES AND GETTING HELP
Enter h or 'h h' for help, or 'man perldebug' for more help.
main::(-e:1): 0
DB<1>
You might find the introduction text varies slightly on your system. For example, the version
number may well be different, and you may have man perldebug or perldoc perldebug. These
are minor differences depending on your Perl installation, the options set under the debugger,
and which version of the debugger you are actively running.
The debugger prompt indicates the number of the command it is waiting for. The command
prompt actually offers more information as program execution continues, but we’ll get to that
in a later chapter. At this point we are in Perl space, or a Perl shell if you like, and can explore our
environment with familiar commands.
Let’s continue our initial investigation of the debugger, by executing a simple Perl command,
print $^0. This is the Perl dollar-caret-zero variable, which displays the operating system
identifier:
DB<2> print 1 / 42
0.0238095238095238
DB<3>
Moving forward, let’s review the library paths searched by Perl for modules:
DB<3> h
This will return a long listing of commands and corresponding instructions available to you
via the debugger. Because this listing isn’t in a format that’s convenient for display in a book,
we’ll summarize these commands in Tables 2-1 through 2-4. Remember also that while this is
a summarized overview, Chapter 15 is a complete and definitive debugger command reference.
CHAPTER 2 ■ INSPECTING VARIABLES AND GETTING HELP 9
At first sight, it may look as though there are too many commands to work out what they
all do, and certainly for a single session, trying to use all of them usefully would be no small
task. Don’t let this put you off. Just as with Perl itself, in normal usage one might expect to use
a comparatively small subset of the available commands.
There are various shortcuts for this facility, and you can use any of the following inter-
changeably: man, perldoc, or doc.
SEE ALSO
The IO extension, perlfunc, "I/O Operators" in perlop.
perl v5.8.2 2003-09-30 FileHandle(3)
Manual page FileHandle(3) line 77/128 (END)
DB<6>
most commands are very short, usually consisting of a single letter. They are all designed to be
quick and easy to use, intuitive, and at your fingertips, instead of being long, explicit, and slow.
This can take a short while to get used to, as a new bunch of commands need to be learned, but
once you understand them the convenience greatly outweighs any perceived issues.
If you don’t like the default commands, you can use the alias command to remap all the
commands to something more suitable for your way of working. The Perl motto, TMTOWTDI
(There’s More Than One Way To Do It), comes to mind. We will see how to use the alias command
in Chapter 12.
Most commands have some form of mnemonic relation to their function. For example instead
of typing the five characters of print, you can use the simple p in its place. Similarly h for help,
l for list, t for trace, and so on. Of course there are a limited number of single letters to use,
although the debugger makes judicious use of upper/lower case and the occasional punctu-
ation mark to good effect.
Keep in mind that when faced with all this new information, new commands, and contexts
(debuggers tend not to be the most beginner-friendly places in even a technical environment),
the best thing to do is to not get stressed by it, but rather to explore and to extend your bound-
aries at your own speed as suits your experience.
DB<10> p $x[1]
second
DB<11>
DB<11> p @x
firstsecondthirdfourthfifth
DB<12>
In this case, that isn’t particularly useful however, as all the elements have been by default
printed out one after the other, with no visible separation, making it hard to see the individual
contents of the variable. We can further resolve this by using a simple Perl join() expression:
All well and good, but a better way to see what is going on inside our variable might be to
use the x command, introduced next.
DB<13> x @x
0 'first'
1 'second'
2 'third'
3 'fourth'
4 'fifth'
DB<14>
That’s better, but it’s still a bit clunky. x is better used by giving it a reference to the variable,
forcing it to be dumped out with the proper indentation and offering much more clarity:
DB<14> x \@x
0 ARRAY(0x83560d0)
0 'first'
1 'second'
2 'third'
3 'fourth'
4 'fifth'
DB<15>
Of course, the same thing can be done with multi-level data structures or objects. It’s when
you can really see what an otherwise complex variable consists of that the indentation really
becomes useful. First we need to create our variable, and to do this, we’re going to take advantage
of the fact that the debugger will accept a multi-line command, if you backslash the newline at
the end of each line. This will simply make the example easier to read, as well as to type:
DB<15> %x = (\
cont: 'this' => 'that',\
cont: 'chars'=> { 'vowels' => qw(a e i o u), 'others' => qw(s q w r k) },\
cont: 'obj' => bless({'_member' => 'variable', '_context' => 'init'}, 'Class'),\
cont: )
DB<16>
We’ll include a self-referential reference too, to see what happens when the debugger
attempts to dump out an infinite loop:
Now when we dump this out, everything becomes much more obvious. Note the
REUSED_ADDRESS memory reference indicated by the hexadecimal number: 0x83ca658. This is
the memory address where the reference to the variable is actually stored, and you can see the
same value both at the head of the hash dump, and at the self ref location for confirmation:
DB<17> x \%x
0 HASH(0x83a50f0)
'chars' => HASH(0x83ca658)
'e' => 'i'
'o' => 'u'
'others' => 's'
'q' => 'w'
14 CHAPTER 2 ■ INSPECTING VARIABLES AND GETTING HELP
Although this variable dump looks a lot like that produced by the standard Perl module used
for dumping complex structures: Data::Dumper, in fact it is produced by a core library called
dumpvar.pl, which Data::Dumper largely supercedes.
If you like, you can take a look at this library by loading it for viewing via the f command,
introduced next.
DB<18> f dumpvar
Choosing /usr/local/lib/perl5/5.8.2/dumpvar.pl matching 'dumpvar':
1 2 3
4 # Needed for PrettyPrinter only:
5
6 # require 5.001; # Well, it coredumps anyway undef DB in 5.000 (not now)
7
8 # translate control chars to ^X - Randal Schwartz
9 # Modifications to print types by Peter Gordon v1.0
10
DB<19>
And to continue listing code and look further down the file, we can use the l (lowercase
letter ell for listing code) command.
DB<19> l
11 # Ilya Zakharevich -- patches after 5.001 (and some before ;-)
12
13 # Won't dump symbol tables and contents of debugged files by default
14
15: $winsize = 80 unless defined $winsize;
16
17
18 # Defaults
19
20 # $globPrint = 1;
DB<19>
CHAPTER 2 ■ INSPECTING VARIABLES AND GETTING HELP 15
If you want to see the code below the chunk that has just been displayed, you can use another
l command, which will continue to list the code from our current position. There are multiple
ways to list code in the debugger via the l command. Use the h l help command to get a com-
plete listing of the possibilities.
DB<19> l
21: $printUndef = 1 unless defined $printUndef;
22: $tick = "auto" unless defined $tick;
23: $unctrl = 'quote' unless defined $unctrl;
24: $subdump = 1;
25: $dumpReused = 0 unless defined $dumpReused;
26: $bareStringify = 1 unless defined $bareStringify;
27
28 sub main::dumpValue {
29: local %address;
30: local $^W=0;
DB<19>
It is important to realize that this is purely a viewing mechanism, and that we are not exe-
cuting code at this point in the viewed file. Rather, we are able to inspect any of the files loaded
into the %INC array via this mechanism. This can, to the uninitiated, lead to some confusion,
because it is very easy to forget exactly where one is in the runtime process. Therefore we have
a reset display command, with which we can remind ourselves.
DB<19> .
main::(-e:1): 0
DB<19>
In this case, the code is simply the integer 0 which we gave on the command line, and the
program name is -e. Later on, when we use a real program, and we can see the program name
and a line of informational code, this may make more sense. The point being made here is that
while the debugger display context was in the other file (dumpvar.pl earlier), it became necessary
to visually return to our current context via the . command.
DB<19> S
Carp::BEGIN
Carp::caller_info
Carp::carp
Carp::cluck
Carp::confess
<...multiple lines snipped here...>
16 CHAPTER 2 ■ INSPECTING VARIABLES AND GETTING HELP
warnings::register::import
warnings::register::mkMask
warnings::unimport
warnings::warn
warnings::warnif
DB<19>
Because the resulting list tends to be so long, you would normally pipe the output through
a pager, with the | command, exactly as we did previously for the | h command. Alternatively
we can reduce the result set altogether by using the S command and giving it a regular expression,
or regex, as an argument. Note that whatever string follows the S command is the actual regex,
that is, the forward slashes (/) you may be used to surrounding a regex with, will be included in
the regex if given. Here the command displays all subroutines that include BEGIN in the name:
DB<19> S BEGIN
Carp::BEGIN
IO::BEGIN
IO::Handle::BEGIN
SelectSaver::BEGIN
Symbol::BEGIN
Term::Cap::BEGIN
Term::ReadLine::BEGIN
main::BEGIN
vars::BEGIN
warnings::BEGIN
DB<20>
Of course anywhere you can use a regex, you can negate one too, by using the exclamation
mark. In this case the command displays all subroutine names which do not include an a, or
an e, or a u character in their name.
DB<20> S ![aeu]
IO::BEGIN
IO::import
Symbol::BEGIN
strict::bits
strict::import
DB<21>
In a similar manner the debugger provides a way to inspect the available variables in a given
namespace. As in the preceding example, this also takes a regex as an optional argument to make
finding the appropriate variable’s easier.
DB<21> V main x
@x = (
0 'first'
1 'second'
2 'third'
3 'fourth'
4 'fifth'
)
%x = (
'chars' => HASH(0x836a0ec)
'e' => 'i'
'o' => 'u'
'others' => 's'
'q' => 'w'
'r' => 'k'
'vowels' => 'a'
'obj' => Class=HASH(0x83c31c0)
'_context' => 'init'
'_member' => 'variable'
'this' => 'that'
)
DB<22>
DB<24> H
21: V main x
20: S ![aeu]
19: S BEGIN
18: f dumpvar
17: x \%x
16: $x{'self ref'} = \%x
15: %x = (
'this' => 'that',
'chars'=> { 'vowels' => qw(a e i o u), 'others' => qw(s q w r k) },
'obj' => bless({'_member' => 'variable', '_context' => 'init'}, 'Class'),
)
14: x @x
13: x \@x
12: p join(' ', @x)
11: p @x
10: p $x[1]
9: @x = qw(first second third fourth fifth)
8: doc FileHandle
7: | h h
6: print "still running...\n"
5: h a
4: print 1 / 0
3: print join("\n", @INC)
2: print 1 / 42
1: print $^O
DB<24>
Unfortunately, the standard history mechanism discards every command that is only a single
character, or less, in length. Presumably this is an unfortunate optimization of some kind, but
therefore you may sometimes wonder where a particular command sequence has disappeared
to. Rest assured that if you use the save, source, and rerun commands, they will honor the real
history list, but it’s something to be aware of.
DB<24> !6
print "still running...\n"
still running...
DB<25>
The most recent command may be replayed by using !!, and previous commands may also be
referred to by the number'th-to-last command or by a regex, which is of course a little more risky.
Note that to use the arrow keys to work with the command history it is necessary to have
the Term::ReadKey module installed. Although this doesn’t offer vi-like command line editing, it
is still very useful to have available, and worth the minimal trouble of installing.
CHAPTER 2 ■ INSPECTING VARIABLES AND GETTING HELP 19
Installing this module via the CPAN could be done with a command like this:
To supply further runtime arguments to Perl, to add an extra library path (-I...) or a module
name (-M...) for example, simply include them after the Perl binary name and before the pro-
gram to debug name. The sequential order of these commands is otherwise largely irrelevant. To
read more about Perl runtime switches, see perldoc perlrun.
Summary
In this chapter we have shown several of the most common commands available to list both
your code and the libraries it uses. You now know how to inspect any of the variables in your
package or in any other package, at runtime.
You can now find out which methods and subroutines are available at any place in the
program, either to a particular object or to a class. You can repeat recent commands or one
which was run much earlier in the program and you know it would be laborious to have to
type in all over again—now you can simply use the command history mechanism.
Finally, you know how to query the debugger help and the system manpages, to find an expla-
nation of any available command or system call, while your program is running and while you
retain control over it.
While this chapter has been primarily concerned with observing the runtime execution of
your program, the next chapter discusses how to control it.
CHAPTER 3
■■■
—Julius Caesar in Rome, celebrating his triumph over King Pharnaces of Pontus
C aesar did not conquer Gaul, consolidate the Roman Empire, and subjugate all his enemies by
allowing them to do whatever they wished. Whatever we may think of his methods, he certainly
took control of his environment and made it behave according to his intentions, much as we try
to do as programmers every day—we control the programs we write. In the same manner, we can
use Perl debugger commands to extend control of the runtime execution of our Perl program to
regions that either need the control but don’t know it, or that have slipped by unnoticed. We’ll
show you how to conquer those bugs.
In this chapter, we demonstrate how to control the execution of your program. You’ll learn
how to set a breakpoint on a variable or a line, interrupt code execution under certain conditions,
make the program do something at a particular point when a variable changes value, and how
to move to different points in your code, (or in someone else’s code), via a used library or module.
Note that in this chapter we are not trying to fix any code—the sole purpose here is to learn
how to control the execution of your Perl code at runtime.
21
22 CHAPTER 3 ■ CONTROLLING PROGRAM EXECUTION
■Note You are always encouraged to experiment by either executing the commands as given or trying your
own variations. This will help you learn how to move about the debugger with confidence. There’s no point in
reading how to use it, unless you actually do use it.
01 #!/usr/bin/perl
02 #
03 # prints the line number and the number of consonants, vowels and special
04 # characters found on each line of the filename given as an argument.
05
06 use strict;
07 use FileHandle;
08
09 my $file = $ARGV[0] || '';
10 my $verbose = $ARGV[1] || 0;
11
12 unless (-f $file) {
13 die("Usage: $0 filename [-v]");
14 }
15 my $FH = FileHandle->new("< $file") or die("unable to open file($file): $!");
16
17 my $i_cnt = 0;
18 my $i_cons = 0;
19 my $i_vows = 0;
20 my $i_spec = 0;
21
22 # parse the file
23 while (<$FH>) {
24 my $line = $_;
25 $i_cons += my $cons = &parse($line, '[bcdfghjklmnpqrstvwxyz]');
26 $i_vows += my $vows = &parse($line, '[aeiou]');
27 $i_spec += my $spec = &parse($line, '[^a-z0-9\s]');
28 print sprintf('%6d', $i_cnt).':'.
29 ' hard'.('.'x(8-length($cons))).$cons.
30 ' soft'.('.'x(8-length($vows))).$vows.
31 ' spec'.('.'x(8-length($spec))).$spec;
32 print $verbose ? " $line" : "\n";
33 $i_cnt++;
34 }
35
36 print ' total:'.
37 ' hard'.(' 'x(8-length($i_cons))).$i_cons.
38 ' soft'.(' 'x(8-length($i_vows))).$i_vows.
39 ' spec'.(' 'x(8-length($i_spec))).$i_spec.
CHAPTER 3 ■ CONTROLLING PROGRAM EXECUTION 23
40 "\n";
41
42 sub parse {
43 my $str = shift;
44 my $reg = shift;
45 my $cnt = my @cnt = ($str =~ /($reg)/gi);
46 return $cnt;
47 }
48
49 exit 0;
Running charcount
Running Listing 3-1 without any arguments generates the following error and simple usage
information:
Now we’d like to correct the call to include a filename argument. In this case, we use the
walrus file as the input and then generate the typical output from the program to get a feel for
what is expected when you run this program. The walrus file may be downloaded from the Apress
web site along with the rest of the code. We’ve included part of the file listing here for reference.
We picked it because it’s such an entertaining read—how many books on debugging make you
smile?
Although this is hardly rocket science, there is enough mileage in this short program to
comfortably demonstrate simple usage of the debugger and to prepare you for the rest of the book.
Now you’re going to run the Perl debugger on this program to see how you can use the motion
commands to both alter and control its execution.
Here we have stopped on the first runtime executable line of the code, which, from the
information line given, is confirmed as line 9 of our file. The first thing to notice when you run
the debugger is that it always stops at what it considers to be the first executable line of your code.
It will run through all your BEGIN blocks, all your use statements, and any consequential code first.
Only then will it stop and wait for your instructions. This is not entirely true—you can actually
get it to stop in a library or module that you are about to load, but we cover that sort of advanced
technique later on.
Looking Backward
We can review code that has already been executed by using the - (list previous code) command:
DB<1> -
01 # $Id: 03.pod,v 1.6 2004/03/15 20:23:19 perltut Exp $
02 #
03 # prints the line number and the number of consonants, vowels and special
04 # characters found on each line of the filename given as an argument.
05
06: use strict;
07: use FileHandle;
08
09==> my $file = $ARGV[0] || '';
10: my $verbose = $ARGV[1] || 0;
DB<1>
Looking Forward
By using the l command introduced in the last chapter, we can see the code we will shortly be
executing.
DB<1> l
11
12: unless (-f $file) {
13: die("Usage: $0 filename [-v]");
14 }
15: my $FH = FileHandle->new("< $file")
or die("unable to open file($file): $!");
16
17: my $i_cnt = 0;
18: my $i_cons = 0;
19: my $i_vows = 0;
20: my $i_spec = 0;
DB<1>
26 CHAPTER 3 ■ CONTROLLING PROGRAM EXECUTION
Looking Sideways
You are not restricted to looking at the next n lines of code, and in fact, you can choose any code
that is currently compiled. To help make this intuitive, Perl makes the l command (lowercase
letter L) very versatile. This command takes a number of different arguments, which can be looked
up by using the h command on it:
DB<1> h l
l min+incr List incr+1 lines starting at min.
l min-max List lines min through max.
l line List single line.
l subname List first window of lines from subroutine.
l $var List first window of lines from subroutine referenced by $var.
l List next window of lines.
DB<2>
For example, let’s use the l command to look at lines 18 through 33:
DB<2> l 18-33
18: my $i_cons = 0;
19: my $i_vows = 0;
20: my $i_spec = 0;
21
22: while (<$FH>) {
23: my $line = $_;
24: $i_cons += my $cons = &parse($line, '[bcdfghjklmnpqrstvwxyz]');
25: $i_vows += my $vows = &parse($line, '[aeiou]');
26: $i_spec += my $spec = &parse($line, '[^a-z0-9\s]');
27: print sprintf('%6d', $i_cnt).':'.
28 ' hard'.('.'x(8-length($cons))).$cons.
29 ' soft'.('.'x(8-length($vows))).$vows.
30 ' spec'.('.'x(8-length($spec))).$spec;
31: print $verbose ? " $line" : "\n";
32: $i_cnt++;
33 }
DB<3>
Although we’re now looking down to line 33, we haven’t actually moved anywhere yet. We can
see that we are actually still way up on line 9 after resetting our display pointer using the . com-
mand:
DB<3> .
main::(./charcount:9): my $file = $ARGV[0] || '';
DB<3>
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookname.com