📄 perldebtut.pod
字号:
=head1 NAMEperldebtut - Perl debugging tutorial=head1 DESCRIPTIONA (very) lightweight introduction in the use of the perl debugger, and apointer to existing, deeper sources of information on the subject of debuggingperl programs. There's an extraordinary number of people out there who don't appear to knowanything about using the perl debugger, though they use the language everyday. This is for them. =head1 use strictFirst of all, there's a few things you can do to make your life a lot morestraightforward when it comes to debugging perl programs, without using thedebugger at all. To demonstrate, here's a simple script with a problem: #!/usr/bin/perl $var1 = 'Hello World'; # always wanted to do that :-) $var2 = "$varl\n"; print $var2; exit;While this compiles and runs happily, it probably won't do what's expected,namely it doesn't print "Hello World\n" at all; It will on the other hand doexactly what it was told to do, computers being a bit that way inclined. Thatis, it will print out a newline character, and you'll get what looks like ablank line. It looks like there's 2 variables when (because of the typo)there's really 3: $var1 = 'Hello World' $varl = undef $var2 = "\n"To catch this kind of problem, we can force each variable to be declaredbefore use by pulling in the strict module, by putting 'use strict;' after thefirst line of the script.Now when you run it, perl complains about the 3 undeclared variables and weget four error messages because one variable is referenced twice: Global symbol "$var1" requires explicit package name at ./t1 line 4. Global symbol "$var2" requires explicit package name at ./t1 line 5. Global symbol "$varl" requires explicit package name at ./t1 line 5. Global symbol "$var2" requires explicit package name at ./t1 line 7. Execution of ./hello aborted due to compilation errors. Luvverly! and to fix this we declare all variables explicitly and now ourscript looks like this: #!/usr/bin/perl use strict; my $var1 = 'Hello World'; my $varl = ''; my $var2 = "$varl\n"; print $var2; exit;We then do (always a good idea) a syntax check before we try to run it again: > perl -c hello hello syntax OK And now when we run it, we get "\n" still, but at least we know why. Justgetting this script to compile has exposed the '$varl' (with the letter 'l)variable, and simply changing $varl to $var1 solves the problem.=head1 Looking at data and -w and wOk, but how about when you want to really see your data, what's in thatdynamic variable, just before using it? #!/usr/bin/perl use strict; my $key = 'welcome'; my %data = ( 'this' => qw(that), 'tom' => qw(and jerry), 'welcome' => q(Hello World), 'zip' => q(welcome), ); my @data = keys %data; print "$data{$key}\n"; exit; Looks OK, after it's been through the syntax check (perl -c scriptname), werun it and all we get is a blank line again! Hmmmm.One common debugging approach here, would be to liberally sprinkle a few printstatements, to add a check just before we print out our data, and another justafter: print "All OK\n" if grep($key, keys %data); print "$data{$key}\n"; print "done: '$data{$key}'\n";And try again: > perl data All OK done: ''After much staring at the same piece of code and not seeing the wood for thetrees for some time, we get a cup of coffee and try another approach. Thatis, we bring in the cavalry by giving perl the 'B<-d>' switch on the commandline: > perl -d data 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::(./data:4): my $key = 'welcome'; Now, what we've done here is to launch the built-in perl debugger on ourscript. It's stopped at the first line of executable code and is waiting forinput.Before we go any further, you'll want to know how to quit the debugger: usejust the letter 'B<q>', not the words 'quit' or 'exit': DB<1> q >That's it, you're back on home turf again.=head1 helpFire the debugger up again on your script and we'll look at the help menu. There's a couple of ways of calling help: a simple 'B<h>' will get you a longscrolled list of help, 'B<|h>' (pipe-h) will pipe the help through your pager('more' or 'less' probably), and finally, 'B<h h>' (h-space-h) will give you ahelpful mini-screen snapshot: DB<1> h h List/search source lines: Control script execution: l [ln|sub] List source code T Stack trace - or . List previous/current line s [expr] Single step [in expr] w [line] List around line n [expr] Next, steps over subs f filename View source in file <CR/Enter> Repeat last n or s /pattern/ ?patt? Search forw/backw r Return from subroutine v Show versions of modules c [ln|sub] Continue until position Debugger controls: L Listbreak/watch/actions O [...] Set debugger options t [expr] Toggle trace [trace expr] <[<]|{[{]|>[>] [cmd] Do pre/post-prompt b [ln|event|sub] [cnd] Set breakpoint ! [N|pat] Redo a previous command d [ln] or D Delete a/all breakpoints H [-num] Display last num commands a [ln] cmd Do cmd before line = [a val] Define/list an alias W expr Add a watch expression h [db_cmd] Get help on command A or W Delete all actions/watch |[|]db_cmd Send output to pager ![!] syscmd Run cmd in a subprocess q or ^D Quit R Attempt a restart Data Examination: expr Execute perl code, also see: s,n,t expr x|m expr Evals expr in list context, dumps the result or lists methods. p expr Print expression (uses script's current package). S [[!]pat] List subroutine names [not] matching pattern V [Pk [Vars]] List Variables in Package. Vars can be ~pattern or !pattern. X [Vars] Same as "V current_package [Vars]". For more help, type h cmd_letter, or run man perldebug for all docs. More confusing options than you can shake a big stick at! It's not as bad asit looks and it's very useful to know more about all of it, and fun too!There's a couple of useful ones to know about straight away. You wouldn'tthink we're using any libraries at all at the moment, but 'B<v>' will showwhich modules are currently loaded, by the debugger as well your script. 'B<V>' and 'B<X>' show variables in the program by package scope and can beconstrained by pattern. 'B<m>' shows methods and 'B<S>' shows all subroutines(by pattern): DB<2>S str dumpvar::stringify strict::bits strict::import strict::unimport Using 'X' and cousins requires you not to use the type identifiers ($@%), justthe 'name': DM<3>X ~err FileHandle(stderr) => fileno(2) Remember we're in our tiny program with a problem, we should have a look atwhere we are, and what our data looks like. First of all let's have a windowon our present position (the first line of code in this case), via the letter'B<w>': DB<4> w 1 #!/usr/bin/perl 2: use strict; 3 4==> my $key = 'welcome'; 5: my %data = ( 6 'this' => qw(that), 7 'tom' => qw(and jerry), 8 'welcome' => q(Hello World), 9 'zip' => q(welcome), 10 ); At line number 4 is a helpful pointer, that tells you where you are now. Tosee more code, type 'w' again: DB<4> w 8 'welcome' => q(Hello World), 9 'zip' => q(welcome), 10 ); 11: my @data = keys %data; 12: print "All OK\n" if grep($key, keys %data); 13: print "$data{$key}\n"; 14: print "done: '$data{$key}'\n"; 15: exit; And if you wanted to list line 5 again, type 'l 5', (note the space): DB<4> l 5 5: my %data = (In this case, there's not much to see, but of course normally there's pages ofstuff to wade through, and 'l' can be very useful. To reset your view to theline we're about to execute, type a lone period '.': DB<5> . main::(./data_a:4): my $key = 'welcome'; The line shown is the one that is about to be executed B<next>, it hasn'thappened yet. So while we can print a variable with the letter 'B<p>', atthis point all we'd get is an empty (undefined) value back. What we need todo is to step through the next executable statement with an 'B<s>': DB<6> s main::(./data_a:5): my %data = ( main::(./data_a:6): 'this' => qw(that), main::(./data_a:7): 'tom' => qw(and jerry), main::(./data_a:8): 'welcome' => q(Hello World), main::(./data_a:9): 'zip' => q(welcome), main::(./data_a:10): ); Now we can have a look at that first ($key) variable: DB<7> p $key welcome line 13 is where the action is, so let's continue down to there via the letter'B<c>', which by the way, inserts a 'one-time-only' breakpoint at the givenline or sub routine: DB<8> c 13 All OK main::(./data_a:13): print "$data{$key}\n";We've gone past our check (where 'All OK' was printed) and have stopped justbefore the meat of our task. We could try to print out a couple of variablesto see what is happening: DB<9> p $data{$key}Not much in there, lets have a look at our hash: DB<10> p %data Hello Worldziptomandwelcomejerrywelcomethisthat DB<11> p keys %data Hello Worldtomwelcomejerrythis Well, this isn't very easy to read, and using the helpful manual (B<h h>), the'B<x>' command looks promising: DB<12> x %data 0 'Hello World' 1 'zip' 2 'tom' 3 'and' 4 'welcome' 5 undef 6 'jerry' 7 'welcome' 8 'this' 9 'that' That's not much help, a couple of welcomes in there, but no indication ofwhich are keys, and which are values, it's just a listed array dump and, inthis case, not particularly helpful. The trick here, is to use a B<reference>to the data structure: DB<13> x \%data 0 HASH(0x8194bc4) 'Hello World' => 'zip' 'jerry' => 'welcome' 'this' => 'that' 'tom' => 'and' 'welcome' => undef The reference is truly dumped and we can finally see what we're dealing with. Our quoting was perfectly valid but wrong for our purposes, with 'and jerry'being treated as 2 separate words rather than a phrase, thus throwing theevenly paired hash structure out of alignment.The 'B<-w>' switch would have told us about this, had we used it at the start,and saved us a lot of trouble: > perl -w data Odd number of elements in hash assignment at ./data line 5. We fix our quoting: 'tom' => q(and jerry), and run it again, this time we getour expected output: > perl -w data Hello WorldWhile we're here, take a closer look at the 'B<x>' command, it's really usefuland will merrily dump out nested references, complete objects, partial objects- just about whatever you throw at it:Let's make a quick object and x-plode it, first we'll start the the debugger:it wants some form of input from STDIN, so we give it something non-commital,a zero: > perl -de 0 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::(-e:1): 0 Now build an on-the-fly object over a couple of lines (note the backslash): DB<1> $obj = bless({'unique_id'=>'123', 'attr'=> \ cont: {'col' => 'black', 'things' => [qw(this that etc)]}}, 'MY_class')And let's have a look at it: DB<2> x $obj 0 MY_class=HASH(0x828ad98) 'attr' => HASH(0x828ad68) 'col' => 'black' 'things' => ARRAY(0x828abb8) 0 'this' 1 'that' 2 'etc' 'unique_id' => 123
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -