perldebug - Perl debugging
Prima di tutto, avete provato ad usare l'opzione -w?
Se non avete mai usato il debugger del Perl, potreste leggere prima
perldebtut, che è un tutorial introduttivo al debugger.
Quando lanciate il Perl con l'opzione -d, i vostri script girano sotto il
Perl debugger. Questo lavora come un ambiente Perl interattivo a linea di
comando, consentendo l'immissione dei comandi del debugger per esaminare il
codice sorgente, settare i breakpoint, analizzare il backtrace dello stack,
cambiare i valori delle variabili, ecc. Ciò è così
conveniente che spesso si lancia il debugger solo per esaminare
interattivamente i costrutti Perl per vedere che cosa fanno. Ad esempio:
$ perl -d -e 42
In Perl, il debugger non è un programma separato come tipicamente
accade negli ambienti compilati. Invece, il flag -d dice al compilatore di
inserire le informazioni (per il debug) del sorgente nell'albero sintattico
che sta per essere passato all'interprete. Questo significa che il vostro
codice deve in primo luogo compilare correttamente affinchè il debugger
possa lavorere su di esso. E quando l'interprete si avvia, precarica una
speciale libreria Perl che contiene il debugger.
Il programma si fermerà a destra del primo comando eseguibile a
tempo di esecuzione (ma si veda più avanti la considerazione a
proposito dei comandi e tempo di compilazione) e vi chiederà di
introdurre un comando del debugger. Contrariamente alle aspettative popolari,
ogni volta che il debugger si ferma e vi mostra una linea di codice, visualizza
sempre la linea che è da eseguire, piuttosto che quella appena
eseguita.
Qualsiasi comando non riconosciuto dal debugger viene direttamente eseguito
(con eval ) come codice Perl nel package corrente. (Il debugger utilizza il
package DB per mantenere le proprie informazioni sullo stato).
Si noti che in tal caso eval è limitata da un implicito scope. Di
conseguenza ogni nuova variabile lessicale introdotta o qualunque modifica al
contenuto del buffer verrà perso dopo l'eval. Il debugger è un
piacevole ambiente per imparare il Perl, ma se sperimentate interattivamente
usando materiale che dovrebbe stare nello stesso scope, mettetelo tutto in una
linea.
Per ogni testo digitato a linea di comando del debugger, gli spazi iniziali e
finali vengono eliminati prima di essere ulteriormente processato. Se il
comando del debugger coincide con una certa funzione del vostro programma,
è sufficiente precedere la funzione con qualcosa che non assomigli a
quel comando, come ; o anche + , oppure racchiudendo il comando tra
parentesi tonde o graffe.
Il debugger accetta i seguenti commandi:
- h
-
Stampa il sommario della pagina di aiuto
- h [comando]
-
Stampa il messaggio di aiuto per il commando del debugger specificato.
- h h
-
Lo speciale argomento
h h stampa l'intera pagina di aiuto, che è
abbastansa lunga.
Se l'output del comando C (o qualsiasi altro comando) occupa più
schermate, precedete il comando con il simbolo pipe (|) in modo da farlo
funzionare attraverso il vostro paginatore, come in:
DB> |h h
Potete cambiare il paginatore utilizzato con il comando o pager=...
- p espressione
-
È come
print {$DB::OUT} espressione nel package corrente. In
particolare, poiché questa è solo la funzione Perl print ,
significa che le strutture dati annidate e gli oggetti non sono ?<dumped>,
diversamente dal comando x .
Il file handle DB::OUT è aperto su /dev/tty, indipendentemente da
dove STDOUT può essere rediretto.
- x [maxdepth] espressione
-
Valuta la relativa espressione in un contesto di lista e stampa i risultati in
un modo piacevole. Le strutture di dati annidate sono stampate ricorsivamente,
differentemente dalla reale fuzione
print del Perl.
Quando si stampano degli hash, probabilmente preferirete usare 'x \%h'
piuttosto che 'x %h'. Si veda Dumpvalue se preferite fare questo
direttamente questo voi stessi.
Il formato dell'output è governato dalle opzioni multiple descritte nel
paragrafo Configurable Options.
Se maxdepth è specificato, deve essere un numero intero N; il
valore è processato ricorsivamente soltanto per N livelli di
profondità, come se l'opzione dumpDepth fosse stata temporaneamente
settata a N.
- V [package [variabili]]
-
Visualizza tutte (o alcune) variabili nel package (?<defaulting to
main >)
stampando i dati in maniera piacevole (gli hash mostrano le loro chiavi e
valori in modo da vedere cosa è cosa, i caratteri di controllo sono resi
stampabili, etc.). Assicuratevi di non usare gli specificatori di tipo (come
$ ) ma solo i nomi dei simboli, ad esempio:
V DB filename line
Usare ~pattern e !pattern ?<for positive and negative regexes>.
Questo è simile ad invocare il comando x su ogni variabile applicabile.
- X [variabili]
-
Equivalente a
V packagecorrente [variabili] .
- y [livello [variabili]]
-
Visualizza tutte (o alcune) variabili lessicali (mnemonico:
mY variabili)
nello scope corrente o in livello scope superiori. Potete limitare le
variabili che vedete con variabili che funziona esattamente come nei comandi
V e X . Richiede versioni 0.08 o superiori del modulo PadWalker ; un
messaggio vi avvertirà nel caso non fosse installato. L'output
è stampato in maniera piacevole nello stesso stile del comando V e
il formato è controllato dalle stesse opzioni.
- T
-
Produce un backtrace dello stack. Vedere più avanti per dettagli
sull'output generato.
- s [espressione]
-
Esecuzione per singoli passi. Esegue la successiva istruzione fino a che non
è stata raggiunta la successiva istruzione discendendo anche nelle
chiamate a subroutine. Se viene fornita un'espressione che contiene delle
chiamate a funzioni, viene valutata anch'essa per singoli passi.
- n [espressione]
-
Esegue la successiva istruzione. Esegue le chiamate di subroutine senza
procedere per singoli passi all'interno di esse fino a che non raggiunge
un'altra istruzione di pari livello (ad es. una chiamata ad un'altra
subroutine). Se viene fornita un'espressione che contiene chiamate a funzioni,
queste verranno eseguite ?<with stops before each statement>.
- r
-
Continua l'esecuzione fino all'uscita della subroutine corrente. Stampa il dump
del valore restituito se l'opzione
PrintRet è settata (default).
- <CR>
-
Ripete l'ultimo comando
n o s .
- c [linea|sub]
-
Continua l'esecuzione, eventualmente inserendo un breakpoint ?<one-time-only>
alla linea o subroutine specificata.
- l
-
Stampa la successiva schermata di linee.
- l min+incr
-
Stampa
incr+1 linee a partire da min .
- l min-max
-
Stampa le linee dalla
min alla max . l - è equivalente a - .
- l linea
-
Stampa la singola linea.
- l subname
-
Stampa la prima schermata di linee dalla subroutine subname. subname
può anche essere una variabile che contiene un riferimento ad una
subroutine.
- -
-
Stampa la precedente schermata di linee.
- v [linea]
-
Stampa alcune linee di codice attorno alla linea corrente (o specificata).
- .
-
Restituisce l'indicatore interno debugger all'ultima linea
eseguita e stampa quella linea.
- f nomefile
-
Passa a visualizzare un file differente o
eval istruzione. Se
nomefile non è un nome completo presente nei valori di %INC, è considerato
un'espressione regolare.
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.
eval ed strings (when accessible) are considered to be filenames:
f (eval 7) and f eval 7\b access the body of the 7th eval ed string
(in the order of execution). The bodies of the currently executed eval
and of eval ed strings that define subroutines are saved and thus
accessible.
- /pattern/
-
Ricerca in avanti il pattern specificato (una espressione regolare Perl); lo /
finale è opzionale. La ricerca è per default case-insensitive.
- ?pattern?
-
Ricerca all'indietro il pattern specificato; il ? finale è opzionale. La
ricerca è per default case-insensitive.
- L [abw]
-
Elenca le azioni, breakpoint e ?<watch expressions> (per default vengono
elencati tutti i tipi)
- S [[!]regex]
-
Stampa tutti i nomi di subroutine che matchano [o no] l'espressione regolare
regex
- t
-
Abilita/disabilita la modalità trace (vedere anche l'opzione
AutoTrace ).
- t espressione
-
Esegue il trace con l'esecuzione di
espressione .
Vedere perldebguts/``Frame Listing Output Examples'' per esempi.
- b
-
Imposta un breakpoint alla linea corrente
- b [linea] [condizione]
-
Imposta un breakpoint prima della linea specificata. Se la condizione è
specificata, viene valutata ogni volta che l'istruzione è raggiunta:
il breakpoint è mantenuto solo se la condizione è vera. I
breakpoint possono essere impostati solo nelle linee che contengono
un'istruzione. Nelle condizioni non usare l'istruzione
if :
b 237 $x > 30
b 237 ++$count237 < 11
b 33 /pattern/i
- b nomesub [condizione]
-
Imposta un breakpoint prima della prima linea della subroutine nomesub.
nomesub può essere una variabile contenente un riferimento a del
codice (in questo caso non è possibile definire una condizione).
- b postpone nomesub [condizione]
-
Imposta un breakpoint alla prima linea della subroutine nomesub dopo che
è stata compilata.
- b load filename
-
Imposta un breakpoint prima della prima linea eseguita di filename che
dovrebbe essere un nome di file completo trovato fra i valori di %INC.
- b compile subname
-
Imposta un breakpoint prima della prima istruzione eseguita dopo che la
subroutine specificata è stata compilata.
- B linea
-
Cancella il breakpoint dalla linea linea.
- B *
-
Cancellla tutti i breakpoint impostati.
- a [linea] comando
-
Imposta un'azione da fare prima che la linea specificata venga eseguita. Se
linea non viene specificata, l'azione viene impostata alla linea che sta per
essere esguita. La sequenza dei passi compiuti del debugger è la
seguente:
1. controlla se c'E<egrave> un breakpoint alla linea specificata
2. stampa la linea se necessario (tracing)
3. esegue ogni azione associata a tale linea
4. prompt user if at a breakpoint or in single-step
5. valuta la linea
Per esempio, il seguente comando stamperà $foo ogni volta che la linea
è passata:
a 53 print "DB FOUND $foo\n"
- A linea
-
Cancella un'azione dalla linea specificata.
- A *
-
Cancella tutte le azioni installate.
- w espr
-
Aggiunge una espressione di watch globale. Speriamo che voi sappiate cosa
sia una di queste, dal momento che si suppone che siano ovvie.
Add a global watch-expression. We hope you know what one of these
is, because they're supposed to be obvious.
- W espr
-
Cancella la watch-expression
- W *
-
Cancella tutte le expressioni di watch.
- o
-
Visualizza tutte le opzioni
- o booloption ...
-
Imposta l'opzione di tipo booleano 'booloption' con il valore
1 .
È possibile settare più opzioni contemporaneamente.
- o opzione? ...
-
Stampa il valore dell'opzione 'opzione'. È possibile indicare
più opzioni contemporaneamente.
- o opzione=valore ...
-
Imposta il valore di una più opzioni. Se il valore contiene uno spazio,
tale valore dovrebbe essere quotato. Per esempio, potreste impostare
o
pager="less -MQeicsNfr" per chiamare il programma less con quelle
specifiche opzioni.
Potete usare apici singoli o doppi, ma dovete mettere un escape in
corrispondenza di tutte le occorrenze degli apici (che avete scelto di usare
per quotare) presenti alli'interno del valore dell'opzione. Allo stesso modo,
dovete mettere un escape agli eventuali caratteri di escape che non siano
intesi come gli escape utilizzati per l'escape degli apici.
?<In other words, you follow single-quoting rules irrespective of the quote;>
Ad esempio: o opzione='Questo non e\' cattivo' o o opzione="Disse,
\"Non e' cosE<igrave>?\"" .
Per motivi storici, =valore è opzionale e, se non presente, per
default l'opzione viene settata a 1 solo dove è sicuro fare in tal
modo, cioè principalmente per le opzioni di tipo booleano.
È sempre meglio assegnare uno specifico valore usando = . L'opzione
opzione può essere abbreviata ma per chiarezza probabilmente non
dovrebbe essere fatto.
Più opzioni possono essere impostate contemporaneamente. Si veda il
paragrafo Opzioni Configurabili per la lista delle opzioni.
- < ?
>
-
Elenca tutte le azioni (comandi Perl) pre-prompt (NdT, cioè impostate per
essere eseguite prima di ogni prompt del debugger)
- < [ comando ]
>
-
Imposta un'azione (comando Perl) che verrà eseguita prima di ogni prompt del
debugger. Un comando multilinea può essere specificato anteponendo il backslash
(NdT '\') ai caratteri di nuova linea.
- < *
>
-
Elimina tutte le azioni (comandi Perl) pre-prompt.
- << command
>
-
Aggiunge un'azione (comando Perl) che verrà eseguita prima di ogni prompt del
debugger. Un comando multilinea può essere specificato anteponendo il backslash
(NdT, '\') ai caratteri di nuova linea.
- > ?
>>
-
Elenca tutte le azioni (comandi Perl) post-prompt (cioè impostate per essere
eseguite prima di ogni prompt del debugger).
- > command
>>
-
Imposta un'azione (comando Perl) che verrà eseguita dopo il prompt del debugger
quando avete appena dato un comando per ritornare all'esecuzione dello script.
Un comando multilinea può essere specificato anteponendo il backslash (NdT,
'\') ai caratteri di nuova linea.
- > *
>>
-
Elimina tutte le azioni (comandi Perl) post-prompt.
- >> command
> >>>
-
Aggiunge un'azione (comando Perl) che verrà eseguita dopo il prompt del
debugger quando avete appena dato un comando per ritornare all'esecuzione dello
script. Un comando multilinea può essere specificato anteponendo il backslash
(NdT, '\') ai caratteri di nuova linea.
- { ?
-
Elenca tutti i
List out pre-prompt debugger commands.
- { [ command ]
-
Imposta un'azione (comando del debugger) che verrà eseguita prima di ogni
prompt del debugger. Un comando multilinea può essere specificato nella maniera
consueta ?<customary fashion>.
Poiché questo comando è in un certo senso nuovo, viene generato un avvertimento
nel caso aveste accidentalmente inserito piuttosto un blocco di istruzioni.
Se è questo che intendevate fare, scrivetelo come ;{ . } o anche do {
... } .
- { *
-
Elimina tutti i comandi pre-prompt del debugger.
- {{ command
-
Aggiunge un'azione (comando del debugger) che verrà eseguita prima di ogni
prompt del debugger. Un comando multilinea può essere inserito, se riuscite ad
indovinare come: si veda più sopra.
- ! numero
-
Riesegue un precedente comando (per default riesegue l'ultimo comando).
- ! -numero
-
Riesegue il numero-esimo precedente comando.
- ! pattern
-
Ripete l'ultimo comando che inizia con il pattern indicato.
Si venda anche
o recallCommand .
- !! cmd
-
Esegue cmd in un sottoprocesso (legge da DB::IN, scrive su DB::OUT). Si veda
anche
o shellBang . Si noti che verrà usata la shell corrente
dell'utente (o meglio, la sua variabile $ENV{SHELL} ), la quale potrebbe
interferire sia con la corretta interpretazione del segnale o stato di uscita
che con le informazioni di coredump.
- source file
-
Legge ed esegue commandi del debugger dal file.
Il file file può a sua volta contenere comandi
source .
- H -numero
-
Visualizza gli ultimi n comandi. Solo i comandi più lunghi di un
carattere vengono listati. Se numero viene omesso, vengono listati tutti.
- q oppure ^D
-
Esce dal debugger. (``quit'' non funziona per questo, a meno che abbiate fatto
un alias).
Questo è l'unico modo supportato per uscire dal debugger, anche se
digitando
exit due volte potrebbe funzionare.
Impostate l'opzione inhibit_exit a 0 se desiderate poter uscire alla fine dello
script. Potreste anche avere bisogno di settare $finished a 0 se volete uscire
con distruzione globale. ?<if you want to step through global destruction>
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
-
Riavvia il debugger tramite un
exec() in una nuova sessione. Il debugger
cercherà di mantenere la vostra storia attraverso ciò, ma le
impostazioni interne e le opzioni a linea di comando potrebbero andare perse.
Le seguenti impostazioni sono attualmente mantenute: la storia, i breakpoint,
le azioni, le opzioni del debugger e le opzioni Perl a linea di comando -w,
-I e -e.
- |dbcmd
-
Esegue il comando del debugger, ridirigendo DB::OUT nel vostro paginatore
corrente.
- ||dbcmd
-
Come
|dbcmd ma DB::OUT è temporaneamente ?<temporarily select ed
as well.>
- = [alias valore]
-
Definisce un alias, ad esempio
= quit q
oppure visualizza la lista degli alias correnti.
- comando
-
Esegue il comando come istruzione Perl. Un punto e virgola trailing
potrà essere fornito. Se l'istruzione Perl fosse al contrario confusa
con un comando del debugger potete utilizzate anche un punto e virgola davanti.
- m espressione
-
Elenca quali metodi possono essere chiamati sul risultato della valutazione
dell'espressione. L'espressione può essere valutata ad un riferimento
ad un oggetto a cui è stato applicato bless oppure al nome di un
package
- M
-
Visualizza tutti i moduli caricati e le loro versioni.
- man [pagina di manuale]
-
Nonostante il suo nome, questo chiama il vostro sistema di visualizzazione
della documentazione sulla pagina fornita, o sul visualizzatore stesso se
pagina di manuale viene omessa.
Se questo visualizzatore è man, le correnti informazioni di
Configurazione vengono usate per invocare man utilizzando il corretto
MANPATH o l'opzione -M manpath.
Se fallisce la ricerca di pagine di manuale nella forma XXX , vengono cercate
pagine di manuale del tipo perlXXX . Questo consente di digitare man debug
o man op dal debugger.
Sui sistemi tradizionalmente privi di un comando man usabile, il debugger
invoca il comando perldoc. Potrebbe succedere che il debugger non riesca a
trovare perldoc: in tal caso impostante manualmente la variabile $DB::doccmd ad
un qualunque visualizzatore per vedere la documentazione Perl sul vostro sistema.
Questo può essere fatto in un file rc o in un assegnamento diretto.
?<We're still waiting for a working example of something along the lines of:>
$DB::doccmd = 'netscape -remote http://something.here/';
Il debugger ha numerose opzioni configurabili usando il comando o sia
interattivamente che tramite le variabili di ambiente che con un file rc
(./.perldb o ~/.perldb in 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
-
Se settata, stampa il valore restituito dopo il comando
r (default).
ornaments
-
Affects screen appearance of the command line (see the Term::ReadLine manpage).
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
tie d 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
-
Stampa solo i primi N elementi ('' per tutti).
dumpDepth
-
Limita la profondità di ricorsione solo a N livelli durante il dump delle
strutture.
Valori negativi vengono interpretati come infinito. Per default il valore è
infinito.
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 perldebguts/``Debugger Internals'' for details.
- 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.
- Comandi multilinea
-
Se volete lanciare un comando multilinea, come una definizione di subroutine
con più istruzioni o un format, mettete un backslash per fare l'escape
del carattere di fine linea che normalmente indica la fine del comando del
debugger.
Ecco un esempio:
DB<1> for (1..4) { \
cont: print "ok\n"; \
cont: }
ok
ok
ok
ok
Notate che questo genere di escape del carattere di fine linea è
specifico per i comandi interattivi digitati nel debugger.
Note that this business of escaping a newline is specific to interactive
commands typed into the debugger.
- Backtrace dello Stack
-
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.
Se avete istruzioni eseguibili a tempo di compilazione (come del codice in
blocchi BEGIN e CHECK o istruzioni use ), queste non verranno stoppate dal
debugger, sebbene questo non accada per require e i blocchi INIT e le
istruzioni a tempo di compilazione possano essere tracciate con l'opzione
AutoTrace impostata in PERLDB_OPTS . Dal vostro codice Perl, tuttavia,
potete trasferire il controllo al debugger usando la seguente istruzione, che
è innocua se il debugger non è in esecuzione:
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 require s 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;
Questo è equivalente ad aver digitato il comando s mentre impostare
$DB::single a 2 è equivalente al comando n . La variabile
$DB::trace dovrebbe essere impostata a 1 per simulare il comando t .
Un altro modo per fare il debug di codice a tempo di compilazione è
quello di avviare il debugger, impostare un breakpoint al caricamento di
qualche modulo:
DB<7> b load f:/perllib/lib/Carp.pm
Will stop on load of `f:/perllib/lib/Carp.pm'.
e riavviare il debugger usando il comando R (se possibile). Si può
usare b compile subname per lo stesso scopo.
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.
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.
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.
Se desiderate utilizzare un debugger alternativo, è sufficiente chiamare
il vostro script specificando il package, preceduto da due punti, come
argomento dell'opzione <-d>.
I più popolare debugger alternativo per il Perl è il profiler del Perl.
Devel:: DProf è ora incluso nella distribuzione standard del Perl.
Per per profilare il vostro programma Perl mycode.pl digitare:
$ perl -d:DProf mycode.pl
Una volta terminato il programma, il profiler scriverà le informazioni di
profilazione nel file tmon.out. Un strumento come dprofpp, anch'esso
incluso nella distribuzione standard del Perl, può essere usato per interpretare
tali informazioni.
Con use re 'debug' si abilita la visualizzazione particolareggiata
di come funziona il motore di espressioni regolari del Perl.
Per capire questa uscita tipico voluminosa, uno non deve soltanto avere certa
idea circa come gli impianti di corrispondenza di espressione normale in
generale, ma inoltre sanno le espressioni normali del Perl internamente sono
compilate in un'automazione. Questi argomenti sono esplorati in dettaglio
certo nelle espressioni normali di perldebguts/``Debugging ''.
Questi argomenti sono trattati in dettaglio in perldebguts/``Debugging regular expressions''.
use re 'debug' ti permette di vedere in dettaglio come funziona il
motore delle espressioni regolari del Perl. Per comprendere l'output,
generalmente molto voluminoso, non solo è necessario avere qualche idea su come
funziona in generale il matching delle espressioni regolari, ma bisogna anche
conoscere come le espressioni regolari del Perl vengono internamente compilate.
Questi argomenti sono esplorati più in dettaglio in
perldebguts/``Debugging regular expressions''.
Il Perl contiene internamente un supporto per il report del suo uso di
memoria,ma questo è un aspetto abbastanza avanzato che richiede una
certa comprensione sul funzionamento dell'allocazione di memoria.
Si veda perldebguts/``Debugging Perl memory usage'' per maggiori dettagli.
Avete provato l'opzione -w switch, no?
?<didn't you?>
perldebtut,
perldebguts,
re,
DB,
the Devel::DProf manpage,
dprofpp,
Dumpvalue,
e
perlrun.
Quando state eseguendo il debugging di uno script che usa la shebang #! e lo
script è normalmente trovato in $PATH, l'opzione -S induce perl a
cercarlo in $PATH, così voi non dovete digitare tutto il percorso o
lanciare which $scriptname .
$ perl -Sd foo.pl
You cannot get stack frame information or in any fashion debug functions
that were not compiled by Perl, such as those from C or C++ extensions.
Non potete ottenere informazioni della struttura dello stack o da funzioni
di debug che non siano state compilate dal Perl, ad esempio quelle di
estensioni C o C++.
Se modificate gli argomenti @_ in una subroutine (così come con shift
o pop ), il backtrace dello stack non visualizzerà i valori orginali.
Il debugger attualmente non funziona correttamente con il parametro a linea di
comando -w poiché il debugger stesso non è esente da warning.
If you're in a slow syscall (like wait ing, accept ing, or read ing
from your keyboard or a socket) and haven't set up your own $SIG{INT}
handler, then you won't be able to CTRL-C your way back to the debugger,
because the debugger's own $SIG{INT} handler doesn't understand that
it needs to raise an exception to longjmp(3) out of slow syscalls.
La versione su cui si basa questa traduzione è ottenibile con:
perl -MPOD2::IT -e print_pod perldebug
Per maggiori informazioni sul progetto di traduzione in italiano si veda
http://pod2it.sourceforge.net/ .
Traduzione a cura di Enrico Sorcinelli <bepi at perl.it>.
Revisione a cura di ... .
Mon Jun 11 22:02:20 2012
|