This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
[perl5db-refactor] Merge two conditionals.
[perl5.git] / lib / perl5db.pl
index 889f305..a0976e1 100644 (file)
@@ -1,5 +1,5 @@
 
-=head1 NAME 
+=head1 NAME
 
 perl5db.pl - the perl debugger
 
@@ -22,7 +22,7 @@ a number of reasons for this, many stemming out of the debugger's history.
 When the debugger was first written, Perl didn't have a lot of its nicer
 features - no references, no lexical variables, no closures, no object-oriented
 programming. So a lot of the things one would normally have done using such
-features was done using global variables, globs and the C<local()> operator 
+features was done using global variables, globs and the C<local()> operator
 in creative ways.
 
 Some of these have survived into the current debugger; a few of the more
@@ -34,7 +34,7 @@ on the comments themselves.
 Experienced Perl programmers will note that the debugger code tends to use
 mostly package globals rather than lexically-scoped variables. This is done
 to allow a significant amount of control of the debugger from outside the
-debugger itself.       
+debugger itself.
 
 Unfortunately, though the variables are accessible, they're not well
 documented, so it's generally been a decision that hasn't made a lot of
@@ -46,9 +46,9 @@ API, but for now, the variables are what we've got.
 
 =head2 Automated variable stacking via C<local()>
 
-As you may recall from reading C<perlfunc>, the C<local()> operator makes a 
+As you may recall from reading C<perlfunc>, the C<local()> operator makes a
 temporary copy of a variable in the current scope. When the scope ends, the
-old copy is restored. This is often used in the debugger to handle the 
+old copy is restored. This is often used in the debugger to handle the
 automatic stacking of variables during recursive calls:
 
      sub foo {
@@ -59,45 +59,45 @@ automatic stacking of variables during recursive calls:
      }
 
 What happens is that on entry to the subroutine, C<$some_global> is localized,
-then altered. When the subroutine returns, Perl automatically undoes the 
+then altered. When the subroutine returns, Perl automatically undoes the
 localization, restoring the previous value. Voila, automatic stack management.
 
-The debugger uses this trick a I<lot>. Of particular note is C<DB::eval>, 
+The debugger uses this trick a I<lot>. Of particular note is C<DB::eval>,
 which lets the debugger get control inside of C<eval>'ed code. The debugger
 localizes a saved copy of C<$@> inside the subroutine, which allows it to
 keep C<$@> safe until it C<DB::eval> returns, at which point the previous
-value of C<$@> is restored. This makes it simple (well, I<simpler>) to keep 
+value of C<$@> is restored. This makes it simple (well, I<simpler>) to keep
 track of C<$@> inside C<eval>s which C<eval> other C<eval's>.
 
 In any case, watch for this pattern. It occurs fairly often.
 
 =head2 The C<^> trick
 
-This is used to cleverly reverse the sense of a logical test depending on 
+This is used to cleverly reverse the sense of a logical test depending on
 the value of an auxiliary variable. For instance, the debugger's C<S>
-(search for subroutines by pattern) allows you to negate the pattern 
+(search for subroutines by pattern) allows you to negate the pattern
 like this:
 
    # Find all non-'foo' subs:
-   S !/foo/      
+   S !/foo/
 
 Boolean algebra states that the truth table for XOR looks like this:
 
 =over 4
 
-=item * 0 ^ 0 = 0 
+=item * 0 ^ 0 = 0
 
 (! not present and no match) --> false, don't print
 
-=item * 0 ^ 1 = 1 
+=item * 0 ^ 1 = 1
 
 (! not present and matches) --> true, print
 
-=item * 1 ^ 0 = 1 
+=item * 1 ^ 0 = 1
 
 (! present and no match) --> true, print
 
-=item * 1 ^ 1 = 0 
+=item * 1 ^ 1 = 0
 
 (! present and matches) --> false, don't print
 
@@ -105,7 +105,7 @@ Boolean algebra states that the truth table for XOR looks like this:
 
 As you can see, the first pair applies when C<!> isn't supplied, and
 the second pair applies when it is. The XOR simply allows us to
-compact a more complicated if-then-elseif-else into a more elegant 
+compact a more complicated if-then-elseif-else into a more elegant
 (but perhaps overly clever) single test. After all, it needed this
 explanation...
 
@@ -114,20 +114,20 @@ explanation...
 There is a certain C programming legacy in the debugger. Some variables,
 such as C<$single>, C<$trace>, and C<$frame>, have I<magical> values composed
 of 1, 2, 4, etc. (powers of 2) OR'ed together. This allows several pieces
-of state to be stored independently in a single scalar. 
+of state to be stored independently in a single scalar.
 
 A test like
 
     if ($scalar & 4) ...
 
-is checking to see if the appropriate bit is on. Since each bit can be 
+is checking to see if the appropriate bit is on. Since each bit can be
 "addressed" independently in this way, C<$scalar> is acting sort of like
-an array of bits. Obviously, since the contents of C<$scalar> are just a 
+an array of bits. Obviously, since the contents of C<$scalar> are just a
 bit-pattern, we can save and restore it easily (it will just look like
 a number).
 
 The problem, is of course, that this tends to leave magic numbers scattered
-all over your program whenever a bit is set, cleared, or checked. So why do 
+all over your program whenever a bit is set, cleared, or checked. So why do
 it?
 
 =over 4
@@ -137,24 +137,24 @@ it?
 First, doing an arithmetical or bitwise operation on a scalar is
 just about the fastest thing you can do in Perl: C<use constant> actually
 creates a subroutine call, and array and hash lookups are much slower. Is
-this over-optimization at the expense of readability? Possibly, but the 
+this over-optimization at the expense of readability? Possibly, but the
 debugger accesses these  variables a I<lot>. Any rewrite of the code will
 probably have to benchmark alternate implementations and see which is the
-best balance of readability and speed, and then document how it actually 
+best balance of readability and speed, and then document how it actually
 works.
 
 =item *
 
-Second, it's very easy to serialize a scalar number. This is done in 
+Second, it's very easy to serialize a scalar number. This is done in
 the restart code; the debugger state variables are saved in C<%ENV> and then
 restored when the debugger is restarted. Having them be just numbers makes
-this trivial. 
+this trivial.
 
 =item *
 
-Third, some of these variables are being shared with the Perl core 
-smack in the middle of the interpreter's execution loop. It's much faster for 
-a C program (like the interpreter) to check a bit in a scalar than to access 
+Third, some of these variables are being shared with the Perl core
+smack in the middle of the interpreter's execution loop. It's much faster for
+a C program (like the interpreter) to check a bit in a scalar than to access
 several different variables (or a Perl array).
 
 =back
@@ -162,13 +162,13 @@ several different variables (or a Perl array).
 =head2 What are those C<XXX> comments for?
 
 Any comment containing C<XXX> means that the comment is either somewhat
-speculative - it's not exactly clear what a given variable or chunk of 
+speculative - it's not exactly clear what a given variable or chunk of
 code is doing, or that it is incomplete - the basics may be clear, but the
 subtleties are not completely documented.
 
 Send in a patch if you can clear up, fill out, or clarify an C<XXX>.
 
-=head1 DATA STRUCTURES MAINTAINED BY CORE         
+=head1 DATA STRUCTURES MAINTAINED BY CORE
 
 There are a number of special data structures provided to the debugger by
 the Perl interpreter.
@@ -179,27 +179,27 @@ element corresponding to a single line of C<$filename>. Additionally,
 breakable lines will be dualvars with the numeric component being the
 memory address of a COP node. Non-breakable lines are dualvar to 0.
 
-The hash C<%{'_<'.$filename}> (aliased locally to C<%dbline> via glob 
-assignment) contains breakpoints and actions.  The keys are line numbers; 
-you can set individual values, but not the whole hash. The Perl interpreter 
+The hash C<%{'_<'.$filename}> (aliased locally to C<%dbline> via glob
+assignment) contains breakpoints and actions.  The keys are line numbers;
+you can set individual values, but not the whole hash. The Perl interpreter
 uses this hash to determine where breakpoints have been set. Any true value is
 considered to be a breakpoint; C<perl5db.pl> uses C<$break_condition\0$action>.
 Values are magical in numeric context: 1 if the line is breakable, 0 if not.
 
-The scalar C<${"_<$filename"}> simply contains the string C<_<$filename>.
+The scalar C<${"_<$filename"}> simply contains the string C<<< _<$filename> >>>.
 This is also the case for evaluated strings that contain subroutines, or
 which are currently being executed.  The $filename for C<eval>ed strings looks
-like C<(eval 34)> or C<(re_eval 19)>.
+like C<(eval 34).
 
 =head1 DEBUGGER STARTUP
 
 When C<perl5db.pl> starts, it reads an rcfile (C<perl5db.ini> for
 non-interactive sessions, C<.perldb> for interactive ones) that can set a number
 of options. In addition, this file may define a subroutine C<&afterinit>
-that will be executed (in the debugger's context) after the debugger has 
+that will be executed (in the debugger's context) after the debugger has
 initialized itself.
 
-Next, it checks the C<PERLDB_OPTS> environment variable and treats its 
+Next, it checks the C<PERLDB_OPTS> environment variable and treats its
 contents as the argument of a C<o> command in the debugger.
 
 =head2 STARTUP-ONLY OPTIONS
@@ -210,32 +210,32 @@ C<&parse_options("optionName=new_value")>.
 
 =over 4
 
-=item * TTY 
+=item * TTY
 
 the TTY to use for debugging i/o.
 
-=item * noTTY 
+=item * noTTY
 
 if set, goes in NonStop mode.  On interrupt, if TTY is not set,
 uses the value of noTTY or F<$HOME/.perldbtty$$> to find TTY using
 Term::Rendezvous.  Current variant is to have the name of TTY in this
 file.
 
-=item * ReadLine 
+=item * ReadLine
 
 if false, a dummy ReadLine is used, so you can debug
 ReadLine applications.
 
-=item * NonStop 
+=item * NonStop
 
 if true, no i/o is performed until interrupt.
 
-=item * LineInfo 
+=item * LineInfo
 
 file or pipe to print line number info to.  If it is a
 pipe, a short "emacs like" message is used.
 
-=item * RemotePort 
+=item * RemotePort
 
 host:port to connect to on remote host for remote debugging.
 
@@ -279,9 +279,9 @@ is the expanded name of the C<require>d file (as found via C<%INC>).
 =head4 C<$CreateTTY>
 
 Used to control when the debugger will attempt to acquire another TTY to be
-used for input. 
+used for input.
 
-=over   
+=over
 
 =item * 1 -  on C<fork()>
 
@@ -304,7 +304,7 @@ contents of C<@_> when C<DB::eval> is called.
 =head4 C<$frame>
 
 Determines what messages (if any) will get printed when a subroutine (or eval)
-is entered or exited. 
+is entered or exited.
 
 =over 4
 
@@ -328,8 +328,8 @@ protect external modules that the debugger uses from getting traced.
 
 =head4 C<$level>
 
-Tracks current debugger nesting level. Used to figure out how many 
-C<E<lt>E<gt>> pairs to surround the line number with when the debugger 
+Tracks current debugger nesting level. Used to figure out how many
+C<E<lt>E<gt>> pairs to surround the line number with when the debugger
 outputs a prompt. Also used to help determine if the program has finished
 during command parsing.
 
@@ -364,7 +364,7 @@ command mode if it finds C<$signal> set to a true value.
 Controls behavior during single-stepping. Stacked in C<@stack> on entry to
 each subroutine; popped again at the end of each subroutine.
 
-=over 4 
+=over 4
 
 =item * 0 - run continuously.
 
@@ -379,7 +379,7 @@ recursion> occurs.
 
 =head4 C<$trace>
 
-Controls the output of trace information. 
+Controls the output of trace information.
 
 =over 4
 
@@ -402,7 +402,7 @@ Manipulated by the debugger's C<source> command and C<DB::readline()> itself.
 
 =head4 C<@dbline>
 
-Local alias to the magical line array, C<@{$main::{'_<'.$filename}}> , 
+Local alias to the magical line array, C<@{$main::{'_<'.$filename}}> ,
 supplied by the Perl interpreter to the debugger. Contains the source.
 
 =head4 C<@old_watch>
@@ -450,7 +450,7 @@ in the actual hash entry.
 
 Keys are file names; values are bitfields:
 
-=over 4 
+=over 4
 
 =item * 1 - file has a breakpoint in it.
 
@@ -487,10 +487,10 @@ definitions (C<condition\0action>).
 =head1 DEBUGGER INITIALIZATION
 
 The debugger's initialization actually jumps all over the place inside this
-package. This is because there are several BEGIN blocks (which of course 
-execute immediately) spread through the code. Why is that? 
+package. This is because there are several BEGIN blocks (which of course
+execute immediately) spread through the code. Why is that?
 
-The debugger needs to be able to change some things and set some things up 
+The debugger needs to be able to change some things and set some things up
 before the debugger code is compiled; most notably, the C<$deep> variable that
 C<DB::sub> uses to tell when a program has recursed deeply. In addition, the
 debugger has to turn off warnings while the debugger code is compiled, but then
@@ -500,7 +500,7 @@ executing.
 The first C<BEGIN> block simply turns off warnings by saving the current
 setting of C<$^W> and then setting it to zero. The second one initializes
 the debugger variables that are needed before the debugger begins executing.
-The third one puts C<$^X> back to its former value. 
+The third one puts C<$^X> back to its former value.
 
 We'll detail the second C<BEGIN> block later; just remember that if you need
 to initialize something before the debugger starts really executing, that's
@@ -510,6 +510,8 @@ where it has to go.
 
 package DB;
 
+use strict;
+
 BEGIN {eval 'use IO::Handle'}; # Needed for flush only? breaks under miniperl
 
 BEGIN {
@@ -519,7 +521,9 @@ BEGIN {
 }
 
 # Debugger for Perl 5.00x; perl5db.pl patch level:
-$VERSION = '1.37';
+use vars qw($VERSION $header);
+
+$VERSION = '1.39_04';
 
 $header = "perl5db.pl version $VERSION";
 
@@ -530,7 +534,7 @@ $header = "perl5db.pl version $VERSION";
 This function replaces straight C<eval()> inside the debugger; it simplifies
 the process of evaluating code in the user's context.
 
-The code to be evaluated is passed via the package global variable 
+The code to be evaluated is passed via the package global variable
 C<$DB::evalarg>; this is done to avoid fiddling with the contents of C<@_>.
 
 Before we do the C<eval()>, we preserve the current settings of C<$trace>,
@@ -541,26 +545,26 @@ proper context to be used when the eval is actually done.  Afterward, we
 restore C<$trace>, C<$single>, and C<$^D>.
 
 Next we need to handle C<$@> without getting confused. We save C<$@> in a
-local lexical, localize C<$saved[0]> (which is where C<save()> will put 
-C<$@>), and then call C<save()> to capture C<$@>, C<$!>, C<$^E>, C<$,>, 
+local lexical, localize C<$saved[0]> (which is where C<save()> will put
+C<$@>), and then call C<save()> to capture C<$@>, C<$!>, C<$^E>, C<$,>,
 C<$/>, C<$\>, and C<$^W>) and set C<$,>, C<$/>, C<$\>, and C<$^W> to values
-considered sane by the debugger. If there was an C<eval()> error, we print 
-it on the debugger's output. If C<$onetimedump> is defined, we call 
-C<dumpit> if it's set to 'dump', or C<methods> if it's set to 
-'methods'. Setting it to something else causes the debugger to do the eval 
-but not print the result - handy if you want to do something else with it 
+considered sane by the debugger. If there was an C<eval()> error, we print
+it on the debugger's output. If C<$onetimedump> is defined, we call
+C<dumpit> if it's set to 'dump', or C<methods> if it's set to
+'methods'. Setting it to something else causes the debugger to do the eval
+but not print the result - handy if you want to do something else with it
 (the "watch expressions" code does this to get the value of the watch
 expression but not show it unless it matters).
 
-In any case, we then return the list of output from C<eval> to the caller, 
-and unwinding restores the former version of C<$@> in C<@saved> as well 
+In any case, we then return the list of output from C<eval> to the caller,
+and unwinding restores the former version of C<$@> in C<@saved> as well
 (the localization of C<$saved[0]> goes away at the end of this scope).
 
 =head3 Parameters and variables influencing execution of DB::eval()
 
 C<DB::eval> isn't parameterized in the standard way; this is to keep the
 debugger's calls to C<DB::eval()> from mucking with C<@_>, among other things.
-The variables listed below influence C<DB::eval()>'s execution directly. 
+The variables listed below influence C<DB::eval()>'s execution directly.
 
 =over 4
 
@@ -570,14 +574,14 @@ The variables listed below influence C<DB::eval()>'s execution directly.
 
 =item C<$single> - Current state of single-stepping
 
-=item C<$onetimeDump> - what is to be displayed after the evaluation 
+=item C<$onetimeDump> - what is to be displayed after the evaluation
 
 =item C<$onetimeDumpDepth> - how deep C<dumpit()> should go when dumping results
 
 =back
 
 The following variables are altered by C<DB::eval()> during its execution. They
-are "stacked" via C<local()>, enabling recursive calls to C<DB::eval()>. 
+are "stacked" via C<local()>, enabling recursive calls to C<DB::eval()>.
 
 =over 4
 
@@ -585,13 +589,13 @@ are "stacked" via C<local()>, enabling recursive calls to C<DB::eval()>.
 
 =item C<$otrace> - saved value of C<$trace>.
 
-=item C<$osingle> - saved value of C<$single>.      
+=item C<$osingle> - saved value of C<$single>.
 
 =item C<$od> - saved value of C<$^D>.
 
 =item C<$saved[0]> - saved value of C<$@>.
 
-=item $\ - for output of C<$@> if there is an evaluation error.      
+=item $\ - for output of C<$@> if there is an evaluation error.
 
 =back
 
@@ -600,7 +604,7 @@ are "stacked" via C<local()>, enabling recursive calls to C<DB::eval()>.
 The context of C<DB::eval()> presents us with some problems. Obviously,
 we want to be 'sandboxed' away from the debugger's internals when we do
 the eval, but we need some way to control how punctuation variables and
-debugger globals are used. 
+debugger globals are used.
 
 We can't use local, because the code inside C<DB::eval> can see localized
 variables; and we can't use C<my> either for the same reason. The code
@@ -620,6 +624,85 @@ context, so we can use C<my> freely.
 # Fiddling with the debugger's context could be Bad. We insulate things as
 # much as we can.
 
+use vars qw(
+    @args
+    %break_on_load
+    @cmdfhs
+    $CommandSet
+    $CreateTTY
+    $DBGR
+    @dbline
+    $dbline
+    %dbline
+    $dieLevel
+    $evalarg
+    $filename
+    $frame
+    $hist
+    $histfile
+    $histsize
+    $ImmediateStop
+    $IN
+    $inhibit_exit
+    @ini_INC
+    $ini_warn
+    $line
+    $maxtrace
+    $od
+    $onetimeDump
+    $onetimedumpDepth
+    %option
+    @options
+    $osingle
+    $otrace
+    $OUT
+    $packname
+    $pager
+    $post
+    %postponed
+    $prc
+    $pre
+    $pretype
+    $psh
+    @RememberOnROptions
+    $remoteport
+    @res
+    $rl
+    @saved
+    $signal
+    $signalLevel
+    $single
+    $start
+    $sub
+    %sub
+    $subname
+    $term
+    $trace
+    $usercontext
+    $warnLevel
+    $window
+);
+
+# Used to save @ARGV and extract any debugger-related flags.
+use vars qw(@ARGS);
+
+# Used to prevent multiple entries to diesignal()
+# (if for instance diesignal() itself dies)
+use vars qw($panic);
+
+# Used to prevent the debugger from running nonstop
+# after a restart
+use vars qw($second_time);
+
+sub _calc_usercontext {
+    my ($package) = @_;
+
+    # Cancel strict completely for the evaluated code, so the code
+    # the user evaluates won't be affected by it. (Shlomi Fish)
+    return 'no strict; ($@, $!, $^E, $,, $/, $\, $^W) = @saved;'
+    . "package $package;";    # this won't let them modify, alas
+}
+
 sub eval {
 
     # 'my' would make it visible from user code
@@ -757,7 +840,7 @@ command prompt.  The prompt will show: C<[0]> when running under threads, but
 not actually in a thread.  C<[tid]> is consistent with C<gdb> usage.
 
 While running under threads, when you set or delete a breakpoint (etc.), this
-will apply to all threads, not just the currently running one.  When you are 
+will apply to all threads, not just the currently running one.  When you are
 in a currently executing thread, you will stay there until it completes.  With
 the current implementation it is not currently possible to hop from one thread
 to another.
@@ -800,19 +883,10 @@ warn(               # Do not ;-)
     $dumpvar::globPrint,
     $dumpvar::usageOnly,
 
-    # used to save @ARGV and extract any debugger-related flags.
-    @ARGS,
-
     # used to control die() reporting in diesignal()
     $Carp::CarpLevel,
 
-    # used to prevent multiple entries to diesignal()
-    # (if for instance diesignal() itself dies)
-    $panic,
 
-    # used to prevent the debugger from running nonstop
-    # after a restart
-    $second_time,
   )
   if 0;
 
@@ -838,13 +912,15 @@ $trace = $signal = $single = 0;    # Uninitialized warning suppression
 # value when the 'r' command is used to return from a subroutine.
 $inhibit_exit = $option{PrintRet} = 1;
 
-# Default to 1 so the prompt will display the first line.
-$trace_to_depth = 1;
+use vars qw($trace_to_depth);
+
+# Default to 1E9 so it won't be limited to a certain recursion depth.
+$trace_to_depth = 1E9;
 
 =head1 OPTION PROCESSING
 
-The debugger's options are actually spread out over the debugger itself and 
-C<dumpvar.pl>; some of these are variables to be set, while others are 
+The debugger's options are actually spread out over the debugger itself and
+C<dumpvar.pl>; some of these are variables to be set, while others are
 subs to be called with a value. To try to make this a little easier to
 manage, the debugger uses a few data structures to define what options
 are legal and how they are to be processed.
@@ -880,6 +956,8 @@ state.
 
 =cut
 
+use vars qw(%optionVars);
+
 %optionVars = (
     hashDepth     => \$dumpvar::hashDepth,
     arrayDepth    => \$dumpvar::arrayDepth,
@@ -909,7 +987,9 @@ state.
 Third, C<%optionAction> defines the subroutine to be called to process each
 option.
 
-=cut 
+=cut
+
+use vars qw(%optionAction);
 
 %optionAction = (
     compactDump   => \&dumpvar::compactDump,
@@ -944,6 +1024,8 @@ option is used.
 # not in the table. A subsequent patch will correct this problem; for
 # the moment, we're just recommenting, and we are NOT going to change
 # function.
+use vars qw(%optionRequire);
+
 %optionRequire = (
     compactDump => 'dumpvar.pl',
     veryCompact => 'dumpvar.pl',
@@ -1090,8 +1172,11 @@ yet so the parent will give them one later via C<resetterm()>.
 
 # Save the current contents of the environment; we're about to
 # much with it. We'll need this if we have to restart.
+use vars qw($ini_pids);
 $ini_pids = $ENV{PERLDB_PIDS};
 
+use vars qw ($pids $term_pid);
+
 if ( defined $ENV{PERLDB_PIDS} ) {
 
     # We're a child. Make us a label out of the current PID structure
@@ -1123,23 +1208,26 @@ else {
     $term_pid         = $$;
 }
 
+use vars qw($pidprompt);
 $pidprompt = '';
 
 # Sets up $emacs as a synonym for $slave_editor.
+use vars qw($slave_editor);
 *emacs = $slave_editor if $slave_editor;    # May be used in afterinit()...
 
 =head2 READING THE RC FILE
 
-The debugger will read a file of initialization options if supplied. If    
+The debugger will read a file of initialization options if supplied. If
 running interactively, this is C<.perldb>; if not, it's C<perldb.ini>.
 
-=cut      
+=cut
 
 # As noted, this test really doesn't check accurately that the debugger
 # is running at a terminal or not.
 
 my $dev_tty = '/dev/tty';
    $dev_tty = 'TT:' if ($^O eq 'VMS');
+use vars qw($rcfile);
 if ( -e $dev_tty ) {                      # this is the wrong metric!
     $rcfile = ".perldb";
 }
@@ -1171,7 +1259,7 @@ sub safe_do {
     unless ( is_safe_file($file) ) {
         CORE::warn <<EO_GRIPE;
 perldb: Must not source insecure rcfile $file.
-        You or the superuser must be the owner, and it must not 
+        You or the superuser must be the owner, and it must not
         be writable by anyone but its owner.
 EO_GRIPE
         return;
@@ -1235,7 +1323,7 @@ the debugger only handles TCP sockets, X11, OS/2, amd Mac OS X
 
 if (not defined &get_fork_TTY)       # only if no routine exists
 {
-    if ( defined $remoteport ) {                 
+    if ( defined $remoteport ) {
                                                  # Expect an inetd-like server
         *get_fork_TTY = \&socket_get_fork_TTY;   # to listen to us
     }
@@ -1275,7 +1363,7 @@ then sets C<PERLDB_RESTART>. When we start executing again, we check to see
 if C<PERLDB_RESTART> is there; if so, we reload all the information that
 the R command stuffed into the environment variables.
 
-  PERLDB_RESTART   - flag only, contains no restart data itself.       
+  PERLDB_RESTART   - flag only, contains no restart data itself.
   PERLDB_HIST      - command history, if it's available
   PERLDB_ON_LOAD   - breakpoints set by the rc file
   PERLDB_POSTPONE  - subs that have been loaded/not executed, and have actions
@@ -1293,6 +1381,8 @@ back into the appropriate spots in the debugger.
 
 =cut
 
+use vars qw(@hist @truehist %postponed_file @typeahead);
+
 if ( exists $ENV{PERLDB_RESTART} ) {
 
     # We're restarting, so we don't need the flag that says to restart anymore.
@@ -1352,6 +1442,9 @@ to be anyone there to enter commands.
 
 =cut
 
+use vars qw($notty $runnonstop $console $tty $LINEINFO);
+use vars qw($lineinfo $doccmd);
+
 if ($notty) {
     $runnonstop = 1;
        share($runnonstop);
@@ -1460,7 +1553,7 @@ If there is a TTY hanging around from a parent, we use that as the console.
 
     $console = $tty if defined $tty;
 
-=head2 SOCKET HANDLING   
+=head2 SOCKET HANDLING
 
 The debugger is capable of opening a socket and carrying out a debugging
 session over the socket.
@@ -1536,9 +1629,7 @@ and if we can.
     } ## end elsif (from if(defined $remoteport))
 
     # Unbuffer DB::OUT. We need to see responses right away.
-    my $previous = select($OUT);
-    $| = 1;                                  # for DB::OUT
-    select($previous);
+    $OUT->autoflush(1);
 
     # Line info goes to debugger output unless pointed elsewhere.
     # Pointing elsewhere makes it possible for slave editors to
@@ -1547,7 +1638,7 @@ and if we can.
     $LINEINFO = $OUT     unless defined $LINEINFO;
     $lineinfo = $console unless defined $lineinfo;
        # share($LINEINFO); # <- unable to share globs
-       share($lineinfo);   # 
+       share($lineinfo);   #
 
 =pod
 
@@ -1579,12 +1670,12 @@ and then call the C<afterinit()> subroutine if there is one.
 # XXX This looks like a bug to me.
 # Why copy to @ARGS and then futz with @args?
 @ARGS = @ARGV;
-for (@args) {
+for (@args) {
     # Make sure backslashes before single quotes are stripped out, and
     # keep args unless they are numeric (XXX why?)
     # s/\'/\\\'/g;                      # removed while not justified understandably
     # s/(.*)/'$1'/ unless /^-?[\d.]+$/; # ditto
-}
+}
 
 # If there was an afterinit() sub defined, call it. It will get
 # executed in our scope, so it can fiddle with debugger globals.
@@ -1593,6 +1684,8 @@ if ( defined &afterinit ) {    # May be defined in $rcfile
 }
 
 # Inform us about "Stack dump during die enabled ..." in dieLevel().
+use vars qw($I_m_init);
+
 $I_m_init = 1;
 
 ############################################################ Subroutines
@@ -1614,11 +1707,40 @@ see what's happening in any given command.
 
 =cut
 
+use vars qw(
+    $action
+    %alias
+    $cmd
+    $doret
+    $fall_off_end
+    $file
+    $filename_ini
+    $finished
+    %had_breakpoints
+    $incr
+    $laststep
+    $level
+    $max
+    @old_watch
+    $package
+    $rc
+    $sh
+    @stack
+    $stack_depth
+    @to_watch
+    $try
+    $end
+);
+
 sub DB {
 
     # lock the debugger and get the thread id for the prompt
        lock($DBGR);
        my $tid;
+       my $position;
+       my ($prefix, $after, $infix);
+       my $pat;
+
        if ($ENV{PERL5DB_THREADED}) {
                $tid = eval { "[".threads->tid."]" };
        }
@@ -1631,8 +1753,8 @@ sub DB {
         if ($runnonstop) {    # Disable until signal
                 # If there's any call stack in place, turn off single
                 # stepping into subs throughout the stack.
-            for ( $i = 0 ; $i <= $stack_depth ; ) {
-                $stack[ $i++ ] &= ~1;
+            for my $i (0 .. $stack_depth) {
+                $stack[ $i ] &= ~1;
             }
 
             # And we are now no longer in single-step mode.
@@ -1665,43 +1787,48 @@ sub DB {
     # caller is returning all the extra information when called from the
     # debugger.
     local ( $package, $filename, $line ) = caller;
-    local $filename_ini = $filename;
+    $filename_ini = $filename;
 
     # set up the context for DB::eval, so it can properly execute
     # code on behalf of the user. We add the package in so that the
     # code is eval'ed in the proper package (not in the debugger!).
-    local $usercontext =
-      '($@, $!, $^E, $,, $/, $\, $^W) = @saved;' . "package $package;";
+    local $usercontext = _calc_usercontext($package);
 
     # Create an alias to the active file magical array to simplify
     # the code here.
     local (*dbline) = $main::{ '_<' . $filename };
 
     # Last line in the program.
-    local $max = $#dbline;
+    $max = $#dbline;
 
     # if we have something here, see if we should break.
-    if ( $dbline{$line}
-        && _is_breakpoint_enabled($filename, $line)
-        && ( ( $stop, $action ) = split( /\0/, $dbline{$line} ) ) )
     {
+        # $stop is lexical and local to this block - $action on the other hand
+        # is global.
+        my $stop;
 
-        # Stop if the stop criterion says to just stop.
-        if ( $stop eq '1' ) {
-            $signal |= 1;
-        }
+        if ( $dbline{$line}
+            && _is_breakpoint_enabled($filename, $line)
+            && (( $stop, $action ) = split( /\0/, $dbline{$line} ) ) )
+        {
 
-        # It's a conditional stop; eval it in the user's context and
-        # see if we should stop. If so, remove the one-time sigil.
-        elsif ($stop) {
-            $evalarg = "\$DB::signal |= 1 if do {$stop}";
-            &eval;
-            # If the breakpoint is temporary, then delete its enabled status.
-            if ($dbline{$line} =~ s/;9($|\0)/$1/) {
-                _cancel_breakpoint_temp_enabled_status($filename, $line);
+            # Stop if the stop criterion says to just stop.
+            if ( $stop eq '1' ) {
+                $signal |= 1;
             }
-        }
-    } ## end if ($dbline{$line} && ...
+
+            # It's a conditional stop; eval it in the user's context and
+            # see if we should stop. If so, remove the one-time sigil.
+            elsif ($stop) {
+                $evalarg = "\$DB::signal |= 1 if do {$stop}";
+                &eval;
+                # If the breakpoint is temporary, then delete its enabled status.
+                if ($dbline{$line} =~ s/;9($|\0)/$1/) {
+                    _cancel_breakpoint_temp_enabled_status($filename, $line);
+                }
+            }
+        } ## end if ($dbline{$line} && ...
+    }
 
     # Preserve the current stop-or-not, and see if any of the W
     # (watch expressions) has changed.
@@ -1709,7 +1836,7 @@ sub DB {
 
     # If we have any watch expressions ...
     if ( $trace & 2 ) {
-        for ( my $n = 0 ; $n <= $#to_watch ; $n++ ) {
+        for my $n (0 .. $#to_watch) {
             $evalarg = $to_watch[$n];
             local $onetimeDump;    # Tell DB::eval() to not output results
 
@@ -1730,16 +1857,16 @@ Watchpoint $n:\t$to_watch[$n] changed:
 EOP
                 $old_watch[$n] = $val;
             } ## end if ($val ne $old_watch...
-        } ## end for (my $n = 0 ; $n <= ...
+        } ## end for my $n (0 ..
     } ## end if ($trace & 2)
 
 =head2 C<watchfunction()>
 
 C<watchfunction()> is a function that can be defined by the user; it is a
-function which will be run on each entry to C<DB::DB>; it gets the 
+function which will be run on each entry to C<DB::DB>; it gets the
 current package, filename, and line as its parameters.
 
-The watchfunction can do anything it likes; it is executing in the 
+The watchfunction can do anything it likes; it is executing in the
 debugger's context, so it has access to all of the debugger's internal
 data structures and functions.
 
@@ -1747,7 +1874,7 @@ C<watchfunction()> can control the debugger's actions. Any of the following
 will cause the debugger to return control to the user's program after
 C<watchfunction()> executes:
 
-=over 4 
+=over 4
 
 =item *
 
@@ -1815,7 +1942,7 @@ won't cause trouble, and we say that the program is over.
 
 =pod
 
-Special check: if we're in package C<DB::fake>, we've gone through the 
+Special check: if we're in package C<DB::fake>, we've gone through the
 C<END> block at least once. We set up everything so that we can continue
 to enter commands and have a valid context to be in.
 
@@ -1828,21 +1955,19 @@ to enter commands and have a valid context to be in.
             print_help(<<EOP);
 Debugged program terminated.  Use B<q> to quit or B<R> to restart,
   use B<o> I<inhibit_exit> to avoid stopping after program termination,
-  B<h q>, B<h R> or B<h o> to get additional info.  
+  B<h q>, B<h R> or B<h o> to get additional info.
 EOP
 
             # Set the DB::eval context appropriately.
             $package     = 'main';
-            $usercontext =
-                '($@, $!, $^E, $,, $/, $\, $^W) = @saved;'
-              . "package $package;";    # this won't let them modify, alas
+            $usercontext = _calc_usercontext($package);
         } ## end elsif ($package eq 'DB::fake')
 
 =pod
 
 If the program hasn't finished executing, we scan forward to the
 next executable line, print that out, build the prompt from the file and line
-number information, and print that.   
+number information, and print that.
 
 =cut
 
@@ -1855,7 +1980,7 @@ number information, and print that.
                                  # Perl 5 ones (sorry, we don't print Klingon
                                  #module names)
 
-            $prefix = $sub =~ /::/ ? "" : "${'package'}::";
+            $prefix = $sub =~ /::/ ? "" : ($package . '::');
             $prefix .= "$sub($filename:";
             $after = ( $dbline[$line] =~ /\n$/ ? '' : "\n" );
 
@@ -1881,7 +2006,7 @@ number information, and print that.
 
             # Scan forward, stopping at either the end or the next
             # unbreakable line.
-            for ( $i = $line + 1 ; $i <= $max && $dbline[$i] == 0 ; ++$i )
+            for ( my $i = $line + 1 ; $i <= $max && $dbline[$i] == 0 ; ++$i )
             {    #{ vi
 
                 # Drop out on null statements, block closers, and comments.
@@ -1895,7 +2020,7 @@ number information, and print that.
                 $after = ( $dbline[$i] =~ /\n$/ ? '' : "\n" );
 
                 # Next executable line.
-                $incr_pos = "$prefix$i$infix$dbline[$i]$after";
+                my $incr_pos = "$prefix$i$infix$dbline[$i]$after";
                 $position .= $incr_pos;
                 if ($frame) {
 
@@ -1913,7 +2038,7 @@ number information, and print that.
 =pod
 
 If there's an action to be executed for the line we stopped at, execute it.
-If there are any preprompt actions, execute those as well.      
+If there are any preprompt actions, execute those as well.
 
 =cut
 
@@ -1993,6 +2118,9 @@ the new command. This is faster, but perhaps a bit more convoluted.
         #
         # If we have a terminal for input, and we get something back
         # from readline(), keep on processing.
+        my $piped;
+        my $selected;
+
       CMD:
         while (
 
@@ -2024,10 +2152,10 @@ the new command. This is faster, but perhaps a bit more convoluted.
             $signal = 0;
 
             # Handle continued commands (ending with \):
-            $cmd =~ s/\\$/\n/ && do {
+            if ($cmd =~ s/\\\z/\n/) {
                 $cmd .= &readline("  cont: ");
                 redo CMD;
-            };
+            }
 
 =head4 The null command
 
@@ -2054,7 +2182,7 @@ it up.
           PIPE: {
                 $cmd =~ s/^\s+//s;    # trim annoying leading whitespace
                 $cmd =~ s/\s+$//s;    # trim annoying trailing whitespace
-                ($i) = split( /\s+/, $cmd );
+                my ($i) = split( /\s+/, $cmd );
 
 =head3 COMMAND ALIASES
 
@@ -2088,21 +2216,21 @@ completely replacing it.
 =head3 MAIN-LINE COMMANDS
 
 All of these commands work up to and after the program being debugged has
-terminated. 
+terminated.
 
 =head4 C<q> - quit
 
-Quit the debugger. This entails setting the C<$fall_off_end> flag, so we don't 
+Quit the debugger. This entails setting the C<$fall_off_end> flag, so we don't
 try to execute further, cleaning any restart-related stuff out of the
 environment, and executing with the last value of C<$?>.
 
 =cut
 
-                $cmd =~ /^q$/ && do {
+                if ($cmd eq 'q') {
                     $fall_off_end = 1;
                     clean_ENV();
                     exit $?;
-                };
+                }
 
 =head4 C<t> - trace [n]
 
@@ -2111,8 +2239,7 @@ If level is specified, set C<$trace_to_depth>.
 
 =cut
 
-                $cmd =~ /^t(?:\s+(\d+))?$/ && do {
-                    my $levels = $1;
+                if (my ($levels) = $cmd =~ /\At(?:\s+(\d+))?\z/) {
                     $trace ^= 1;
                     local $\ = '';
                     $trace_to_depth = $levels ? $stack_depth + $levels : 1E9;
@@ -2121,7 +2248,7 @@ If level is specified, set C<$trace_to_depth>.
                       ? ( $levels ? "on (to level $trace_to_depth)" : "on" )
                       : "off" ) . "\n";
                     next CMD;
-                };
+                }
 
 =head4 C<S> - list subroutines matching/not matching a pattern
 
@@ -2129,11 +2256,13 @@ Walks through C<%sub>, checking to see whether or not to print the name.
 
 =cut
 
-                $cmd =~ /^S(\s+(!)?(.+))?$/ && do {
-
-                    $Srev     = defined $2;     # Reverse scan?
-                    $Spatt    = $3;             # The pattern (if any) to use.
-                    $Snocheck = !defined $1;    # No args - print all subs.
+                if (my ($print_all_subs, $should_reverse, $Spatt)
+                    = $cmd =~ /\AS(\s+(!)?(.+))?\z/) {
+                    # $Spatt is the pattern (if any) to use.
+                    # Reverse scan?
+                    my $Srev     = defined $should_reverse;
+                    # No args - print all subs.
+                    my $Snocheck = !defined $print_all_subs;
 
                     # Need to make these sane here.
                     local $\ = '';
@@ -2149,11 +2278,11 @@ Walks through C<%sub>, checking to see whether or not to print the name.
                         }
                     }
                     next CMD;
-                };
+                }
 
 =head4 C<X> - list variables in current package
 
-Since the C<V> command actually processes this, just change this to the 
+Since the C<V> command actually processes this, just change this to the
 appropriate C<V> command and fall through.
 
 =cut
@@ -2162,27 +2291,28 @@ appropriate C<V> command and fall through.
 
 =head4 C<V> - list variables
 
-Uses C<dumpvar.pl> to dump out the current values for selected variables. 
+Uses C<dumpvar.pl> to dump out the current values for selected variables.
 
 =cut
 
                 # Bare V commands get the currently-being-debugged package
                 # added.
-                $cmd =~ /^V$/ && do {
+                if ($cmd eq "V") {
                     $cmd = "V $package";
-                };
+                }
 
                 # V - show variables in package.
-                $cmd =~ /^V\b\s*(\S+)\s*(.*)/ && do {
+                if (my ($new_packname, $new_vars_str) =
+                    $cmd =~ /\AV\b\s*(\S+)\s*(.*)/) {
 
                     # Save the currently selected filehandle and
                     # force output to debugger's filehandle (dumpvar
                     # just does "print" for output).
-                    local ($savout) = select($OUT);
+                    my $savout = select($OUT);
 
                     # Grab package name and variables to dump.
-                    $packname = $1;
-                    @vars     = split( ' ', $2 );
+                    $packname = $new_packname;
+                    my @vars     = split( ' ', $new_vars_str );
 
                     # If main::dumpvar isn't here, get it.
                     do 'dumpvar.pl' || die $@ unless defined &main::dumpvar;
@@ -2220,7 +2350,7 @@ Uses C<dumpvar.pl> to dump out the current values for selected variables.
                     # Restore the output filehandle, and go round again.
                     select($savout);
                     next CMD;
-                };
+                }
 
 =head4 C<x> - evaluate and print an expression
 
@@ -2229,15 +2359,15 @@ via C<dumpvar.pl> instead of just printing it directly.
 
 =cut
 
-                $cmd =~ s/^x\b/ / && do {    # Remainder gets done by DB::eval()
+                if ($cmd =~ s#\Ax\b# #) {    # Remainder gets done by DB::eval()
                     $onetimeDump = 'dump';    # main::dumpvar shows the output
 
                     # handle special  "x 3 blah" syntax XXX propagate
                     # doc back to special variables.
-                    if ( $cmd =~ s/^\s*(\d+)(?=\s)/ / ) {
+                    if ( $cmd =~ s#\A\s*(\d+)(?=\s)# #) {
                         $onetimedumpDepth = $1;
                     }
-                };
+                }
 
 =head4 C<m> - print methods
 
@@ -2245,22 +2375,21 @@ Just uses C<DB::methods> to determine what methods are available.
 
 =cut
 
-                $cmd =~ s/^m\s+([\w:]+)\s*$/ / && do {
+                if ($cmd =~ s#\Am\s+([\w:]+)\s*\z# #) {
                     methods($1);
                     next CMD;
-                };
+                }
 
                 # m expr - set up DB::eval to do the work
-                $cmd =~ s/^m\b/ / && do {    # Rest gets done by DB::eval()
+                if ($cmd =~ s#\Am\b# #) {    # Rest gets done by DB::eval()
                     $onetimeDump = 'methods';   #  method output gets used there
-                };
+                }
 
 =head4 C<f> - switch files
 
 =cut
 
-                $cmd =~ /^f\b\s*(.*)/ && do {
-                    $file = $1;
+                if (($file) = $cmd =~ /\Af\b\s*(.*)/) {
                     $file =~ s/\s+$//;
 
                     # help for no arguments (old-style was return from sub).
@@ -2302,7 +2431,7 @@ Just uses C<DB::methods> to determine what methods are available.
                         print $OUT "Already in $file.\n";
                         next CMD;
                     }
-                };
+                }
 
 =head4 C<.> - return to last-executed line.
 
@@ -2312,7 +2441,7 @@ and then we look up the line in the magical C<%dbline> hash.
 =cut
 
                 # . command.
-                $cmd =~ /^\.$/ && do {
+                if ($cmd eq '.') {
                     $incr = -1;    # stay at current line
 
                     # Reset everything to the old location.
@@ -2324,7 +2453,7 @@ and then we look up the line in the magical C<%dbline> hash.
                     # Now where are we?
                     print_lineinfo($position);
                     next CMD;
-                };
+                }
 
 =head4 C<-> - back one window
 
@@ -2336,7 +2465,7 @@ C<$start>) in C<$cmd> to be executed later.
 =cut
 
                 # - - back a window.
-                $cmd =~ /^-$/ && do {
+                if ($cmd eq '-') {
 
                     # back up by a window; go to 1 if back too far.
                     $start -= $incr + $window + 1;
@@ -2345,7 +2474,7 @@ C<$start>) in C<$cmd> to be executed later.
 
                     # Generate and execute a "l +" command (handled below).
                     $cmd = 'l ' . ($start) . '+';
-                };
+                }
 
 =head3 PRE-580 COMMANDS VS. NEW COMMANDS: C<a, A, b, B, h, l, L, M, o, O, P, v, w, W, E<lt>, E<lt>E<lt>, {, {{>
 
@@ -2360,19 +2489,20 @@ deal with them instead of processing them in-line.
 
                 # All of these commands were remapped in perl 5.8.0;
                 # we send them off to the secondary dispatcher (see below).
-                $cmd =~ /^([aAbBeEhilLMoOPvwW]\b|[<>\{]{1,2})\s*(.*)/so && do {
-                    &cmd_wrapper( $1, $2, $line );
+                if (my ($cmd_letter, $my_arg) = $cmd =~ /\A([aAbBeEhilLMoOPvwW]\b|[<>\{]{1,2})\s*(.*)/so) {
+                    &cmd_wrapper( $cmd_letter, $my_arg, $line );
                     next CMD;
-                };
+                }
 
 =head4 C<y> - List lexicals in higher scope
 
-Uses C<PadWalker> to find the lexicals supplied as arguments in a scope    
+Uses C<PadWalker> to find the lexicals supplied as arguments in a scope
 above the current one and then displays then using C<dumpvar.pl>.
 
 =cut
 
-                $cmd =~ /^y(?:\s+(\d*)\s*(.*))?$/ && do {
+                if (my ($match_level, $match_vars)
+                    = $cmd =~ /^y(?:\s+(\d*)\s*(.*))?$/) {
 
                     # See if we've got the necessary support.
                     eval { require PadWalker; PadWalker->VERSION(0.08) }
@@ -2390,10 +2520,10 @@ above the current one and then displays then using C<dumpvar.pl>.
                       and next CMD;
 
                     # Got all the modules we need. Find them and print them.
-                    my @vars = split( ' ', $2 || '' );
+                    my @vars = split( ' ', $match_vars || '' );
 
                     # Find the pad.
-                    my $h = eval { PadWalker::peek_my( ( $1 || 0 ) + 1 ) };
+                    my $h = eval { PadWalker::peek_my( ( $match_level || 0 ) + 1 ) };
 
                     # Oops. Can't find it.
                     $@ and $@ =~ s/ at .*//, &warn($@), next CMD;
@@ -2408,7 +2538,7 @@ above the current one and then displays then using C<dumpvar.pl>.
                       for sort keys %$h;
                     select($savout);
                     next CMD;
-                };
+                }
 
 =head3 COMMANDS NOT WORKING AFTER PROGRAM ENDS
 
@@ -2422,12 +2552,12 @@ they can't.
 
 Done by setting C<$single> to 2, which forces subs to execute straight through
 when entered (see C<DB::sub>). We also save the C<n> command in C<$laststep>,
-so a null command knows what to re-execute. 
+so a null command knows what to re-execute.
 
 =cut
 
                 # n - next
-                $cmd =~ /^n$/ && do {
+                if ($cmd eq 'n') {
                     end_report(), next CMD if $finished and $level <= 1;
 
                     # Single step, but don't enter subs.
@@ -2436,17 +2566,17 @@ so a null command knows what to re-execute.
                     # Save for empty command (repeat last).
                     $laststep = $cmd;
                     last CMD;
-                };
+                }
 
 =head4 C<s> - single-step, entering subs
 
-Sets C<$single> to 1, which causes C<DB::sub> to continue tracing inside     
+Sets C<$single> to 1, which causes C<DB::sub> to continue tracing inside
 subs. Also saves C<s> as C<$lastcmd>.
 
 =cut
 
                 # s - single step.
-                $cmd =~ /^s$/ && do {
+                if ($cmd eq 's') {
 
                     # Get out and restart the command loop if program
                     # has finished.
@@ -2458,7 +2588,7 @@ subs. Also saves C<s> as C<$lastcmd>.
                     # Save for empty command (repeat last).
                     $laststep = $cmd;
                     last CMD;
-                };
+                }
 
 =head4 C<c> - run continuously, setting an optional breakpoint
 
@@ -2470,14 +2600,14 @@ in this and all call levels above this one.
 =cut
 
                 # c - start continuous execution.
-                $cmd =~ /^c\b\s*([\w:]*)\s*$/ && do {
+                if (($i) = $cmd =~ m#\Ac\b\s*([\w:]*)\s*\z#) {
 
                     # Hey, show's over. The debugged program finished
                     # executing already.
                     end_report(), next CMD if $finished and $level <= 1;
 
                     # Capture the place to put a one-time break.
-                    $subname = $i = $1;
+                    $subname = $i;
 
                     #  Probably not needed, since we finish an interactive
                     #  sub-session anyway...
@@ -2564,11 +2694,11 @@ in this and all call levels above this one.
                     } ## end if ($i)
 
                     # Turn off stack tracing from here up.
-                    for ( $i = 0 ; $i <= $stack_depth ; ) {
-                        $stack[ $i++ ] &= ~1;
+                    for my $i (0 .. $stack_depth) {
+                        $stack[ $i ] &= ~1;
                     }
                     last CMD;
-                };
+                }
 
 =head4 C<r> - return from a subroutine
 
@@ -2581,7 +2711,7 @@ appropriately, and force us out of the command loop.
 =cut
 
                 # r - return from the current subroutine.
-                $cmd =~ /^r$/ && do {
+                if ($cmd eq 'r') {
 
                     # Can't do anything if the program's over.
                     end_report(), next CMD if $finished and $level <= 1;
@@ -2592,7 +2722,7 @@ appropriately, and force us out of the command loop.
                     # Print return value unless the stack is empty.
                     $doret = $option{PrintRet} ? $stack_depth - 1 : -2;
                     last CMD;
-                };
+                }
 
 =head4 C<T> - stack trace
 
@@ -2600,10 +2730,10 @@ Just calls C<DB::print_trace>.
 
 =cut
 
-                $cmd =~ /^T$/ && do {
+                if ($cmd eq 'T') {
                     print_trace( $OUT, 1 );    # skip DB
                     next CMD;
-                };
+                }
 
 =head4 C<w> - List window around current line.
 
@@ -2611,29 +2741,35 @@ Just calls C<DB::cmd_w>.
 
 =cut
 
-                $cmd =~ /^w\b\s*(.*)/s && do { &cmd_w( 'w', $1 ); next CMD; };
+                if (my ($arg) = $cmd =~ /\Aw\b\s*(.*)/s) {
+                    &cmd_w( 'w', $arg );
+                    next CMD;
+                }
 
 =head4 C<W> - watch-expression processing.
 
-Just calls C<DB::cmd_W>. 
+Just calls C<DB::cmd_W>.
 
 =cut
 
-                $cmd =~ /^W\b\s*(.*)/s && do { &cmd_W( 'W', $1 ); next CMD; };
+                if (my ($arg) = $cmd =~ /\AW\b\s*(.*)/s) {
+                    &cmd_W( 'W', $arg );
+                    next CMD;
+                }
 
 =head4 C</> - search forward for a string in the source
 
-We take the argument and treat it as a pattern. If it turns out to be a 
+We take the argument and treat it as a pattern. If it turns out to be a
 bad one, we return the error we got from trying to C<eval> it and exit.
-If not, we create some code to do the search and C<eval> it so it can't 
+If not, we create some code to do the search and C<eval> it so it can't
 mess us up.
 
 =cut
 
-                $cmd =~ /^\/(.*)$/ && do {
+                # The pattern as a string.
+                use vars qw($inpat);
 
-                    # The pattern as a string.
-                    $inpat = $1;
+                if (($inpat) = $cmd =~ m#\A/(.*)\z#) {
 
                     # Remove the final slash.
                     $inpat =~ s:([^\\])/$:$1:;
@@ -2685,7 +2821,7 @@ mess us up.
                                 if ($slave_editor) {
                                     # Handle proper escaping in the slave.
                                     print $OUT "\032\032$filename:$start:0\n";
-                                } 
+                                }
                                 else {
                                     # Just print the line normally.
                                     print $OUT "$start:\t",$dbline[$start],"\n";
@@ -2698,7 +2834,7 @@ mess us up.
                     # If we wrapped, there never was a match.
                     print $OUT "/$pat/: not found\n" if ( $start == $end );
                     next CMD;
-                };
+                }
 
 =head4 C<?> - search backward for a string in the source
 
@@ -2707,10 +2843,9 @@ Same as for C</>, except the loop runs backwards.
 =cut
 
                 # ? - backward pattern search.
-                $cmd =~ /^\?(.*)$/ && do {
+                if (my ($inpat) = $cmd =~ m#\A\?(.*)\z#) {
 
                     # Get the pattern, remove trailing question mark.
-                    $inpat = $1;
                     $inpat =~ s:([^\\])\?$:$1:;
 
                     # If we've got one ...
@@ -2755,7 +2890,7 @@ Same as for C</>, except the loop runs backwards.
                                 if ($slave_editor) {
                                     # Yep, follow slave editor requirements.
                                     print $OUT "\032\032$filename:$start:0\n";
-                                } 
+                                }
                                 else {
                                     # Yep, just print normally.
                                     print $OUT "$start:\t",$dbline[$start],"\n";
@@ -2769,7 +2904,7 @@ Same as for C</>, except the loop runs backwards.
                     # Say we failed if the loop never found anything,
                     print $OUT "?$pat?: not found\n" if ( $start == $end );
                     next CMD;
-                };
+                }
 
 =head4 C<$rc> - Recall command
 
@@ -2780,7 +2915,7 @@ into C<$cmd>, and redoes the loop to execute it.
 =cut
 
                 # $rc - recall command.
-                $cmd =~ /^$rc+\s*(-)?(\d+)?$/ && do {
+                if (my ($minus, $arg) = $cmd =~ m#\A$rc+\s*(-)?(\d+)?\z#) {
 
                     # No arguments, take one thing off history.
                     pop(@hist) if length($cmd) > 1;
@@ -2789,7 +2924,7 @@ into C<$cmd>, and redoes the loop to execute it.
                     #  Y - index back from most recent (by 1 if bare minus)
                     #  N - go to that particular command slot or the last
                     #      thing if nothing following.
-                    $i = $1 ? ( $#hist - ( $2 || 1 ) ) : ( $2 || $#hist );
+                    $i = $minus ? ( $#hist - ( $arg || 1 ) ) : ( $arg || $#hist );
 
                     # Pick out the command desired.
                     $cmd = $hist[$i];
@@ -2798,7 +2933,7 @@ into C<$cmd>, and redoes the loop to execute it.
                     # with that command in the buffer.
                     print $OUT $cmd, "\n";
                     redo CMD;
-                };
+                }
 
 =head4 C<$sh$sh> - C<system()> command
 
@@ -2809,12 +2944,12 @@ C<STDOUT> from getting messed up.
 
                 # $sh$sh - run a shell command (if it's all ASCII).
                 # Can't run shell commands with Unicode in the debugger, hmm.
-                $cmd =~ /^$sh$sh\s*([\x00-\xff]*)/ && do {
+                if (my ($arg) = $cmd =~ m#\A$sh$sh\s*(.*)#ms) {
 
                     # System it.
-                    &system($1);
+                    &system($arg);
                     next CMD;
-                };
+                }
 
 =head4 C<$rc I<pattern> $rc> - Search command history
 
@@ -2824,17 +2959,16 @@ If a command is found, it is placed in C<$cmd> and executed via C<redo>.
 =cut
 
                 # $rc pattern $rc - find a command in the history.
-                $cmd =~ /^$rc([^$rc].*)$/ && do {
+                if (my ($arg) = $cmd =~ /\A$rc([^$rc].*)\z/) {
 
                     # Create the pattern to use.
-                    $pat = "^$1";
+                    $pat = "^$arg";
 
                     # Toss off last entry if length is >1 (and it always is).
                     pop(@hist) if length($cmd) > 1;
 
                     # Look backward through the history.
                     for ( $i = $#hist ; $i ; --$i ) {
-
                         # Stop if we find it.
                         last if $hist[$i] =~ /$pat/;
                     }
@@ -2850,22 +2984,22 @@ If a command is found, it is placed in C<$cmd> and executed via C<redo>.
                     $cmd = $hist[$i];
                     print $OUT $cmd, "\n";
                     redo CMD;
-                };
+                }
 
-=head4 C<$sh> - Invoke a shell     
+=head4 C<$sh> - Invoke a shell
 
 Uses C<DB::system> to invoke a shell.
 
 =cut
 
                 # $sh - start a shell.
-                $cmd =~ /^$sh$/ && do {
+                if ($cmd =~ /\A$sh\z/) {
 
                     # Run the user's shell. If none defined, run Bourne.
                     # We resume execution when the shell terminates.
                     &system( $ENV{SHELL} || "/bin/sh" );
                     next CMD;
-                };
+                }
 
 =head4 C<$sh I<command>> - Force execution of a command in a shell
 
@@ -2875,15 +3009,15 @@ C<DB::system> to avoid problems with C<STDIN> and C<STDOUT>.
 =cut
 
                 # $sh command - start a shell and run a command in it.
-                $cmd =~ /^$sh\s*([\x00-\xff]*)/ && do {
+                if (my ($arg) = $cmd =~ m#\A$sh\s*(.*)#ms) {
 
                     # XXX: using csh or tcsh destroys sigint retvals!
                     #&system($1);  # use this instead
 
                     # use the user's shell, or Bourne if none defined.
-                    &system( $ENV{SHELL} || "/bin/sh", "-c", $1 );
+                    &system( $ENV{SHELL} || "/bin/sh", "-c", $arg );
                     next CMD;
-                };
+                }
 
 =head4 C<H> - display commands in history
 
@@ -2891,17 +3025,18 @@ Prints the contents of C<@hist> (if any).
 
 =cut
 
-                $cmd =~ /^H\b\s*\*/ && do {
+                if ($cmd =~ /\AH\b\s*\*/) {
                     @hist = @truehist = ();
                     print $OUT "History cleansed\n";
                     next CMD;
-                };
+                }
 
-                $cmd =~ /^H\b\s*(-(\d+))?/ && do {
+                if (my ($num)
+                    = $cmd =~ /\AH\b\s*(?:-(\d+))?/) {
 
                     # Anything other than negative numbers is ignored by
                     # the (incorrect) pattern, so this test does nothing.
-                    $end = $2 ? ( $#hist - $2 ) : 0;
+                    $end = $num ? ( $#hist - $num ) : 0;
 
                     # Set to the minimum if less than zero.
                     $hist = 0 if $hist < 0;
@@ -2916,7 +3051,7 @@ Prints the contents of C<@hist> (if any).
                           unless $hist[$i] =~ /^.?$/;
                     }
                     next CMD;
-                };
+                }
 
 =head4 C<man, doc, perldoc> - look up documentation
 
@@ -2925,10 +3060,11 @@ Just calls C<runman()> to print the appropriate document.
 =cut
 
                 # man, perldoc, doc - show manual pages.
-                $cmd =~ /^(?:man|(?:perl)?doc)\b(?:\s+([^(]*))?$/ && do {
-                    runman($1);
+                if (my ($man_page)
+                    = $cmd =~ /\A(?:man|(?:perl)?doc)\b(?:\s+([^(]*))?\z/) {
+                    runman($man_page);
                     next CMD;
-                };
+                }
 
 =head4 C<p> - print
 
@@ -2937,11 +3073,14 @@ the bottom of the loop.
 
 =cut
 
+                my $print_cmd = 'print {$DB::OUT} ';
                 # p - print (no args): print $_.
-                $cmd =~ s/^p$/print {\$DB::OUT} \$_/;
+                if ($cmd eq 'p') {
+                    $cmd = $print_cmd . '$_';
+                }
 
                 # p - print the given expression.
-                $cmd =~ s/^p\b/print {\$DB::OUT} /;
+                $cmd =~ s/\Ap\b/$print_cmd /;
 
 =head4 C<=> - define command alias
 
@@ -2950,7 +3089,7 @@ Manipulates C<%alias> to add or list command aliases.
 =cut
 
                 # = - set up a command alias.
-                $cmd =~ s/^=\s*// && do {
+                if ($cmd =~ s/\A=\s*//) {
                     my @keys;
                     if ( length $cmd == 0 ) {
 
@@ -3019,7 +3158,7 @@ Manipulates C<%alias> to add or list command aliases.
                         }
                     } ## end for my $k (@keys)
                     next CMD;
-                };
+                }
 
 =head4 C<source> - read commands from a file.
 
@@ -3029,8 +3168,8 @@ pick it up.
 =cut
 
                 # source - read commands from a file (or pipe!) and execute.
-                $cmd =~ /^source\s+(.*\S)/ && do {
-                    if ( open my $fh, $1 ) {
+                if (my ($sourced_fn) = $cmd =~ /\Asource\s+(.*\S)/) {
+                    if ( open my $fh, $sourced_fn ) {
 
                         # Opened OK; stick it in the list of file handles.
                         push @cmdfhs, $fh;
@@ -3038,13 +3177,13 @@ pick it up.
                     else {
 
                         # Couldn't open it.
-                        &warn("Can't execute '$1': $!\n");
+                        &warn("Can't execute '$sourced_fn': $!\n");
                     }
                     next CMD;
-                };
+                }
 
-                $cmd =~ /^(enable|disable)\s+(\S+)\s*$/ && do {
-                    my ($cmd, $position) = ($1, $2);
+                if (my ($which_cmd, $position)
+                    = $cmd =~ /^(enable|disable)\s+(\S+)\s*$/) {
 
                     my ($fn, $line_num);
                     if ($position =~ m{\A\d+\z})
@@ -3052,9 +3191,9 @@ pick it up.
                         $fn = $filename;
                         $line_num = $position;
                     }
-                    elsif ($position =~ m{\A(.*):(\d+)\z})
-                    {
-                        ($fn, $line_num) = ($1, $2);
+                    elsif (my ($new_fn, $new_line_num)
+                        = $position =~ m{\A(.*):(\d+)\z}) {
+                        ($fn, $line_num) = ($new_fn, $new_line_num);
                     }
                     else
                     {
@@ -3064,7 +3203,7 @@ pick it up.
                     if (defined($fn)) {
                         if (_has_breakpoint_data_ref($fn, $line_num)) {
                             _set_breakpoint_enabled_status($fn, $line_num,
-                                ($cmd eq 'enable' ? 1 : '')
+                                ($which_cmd eq 'enable' ? 1 : '')
                             );
                         }
                         else {
@@ -3073,7 +3212,7 @@ pick it up.
                     }
 
                     next CMD;
-                };
+                }
 
 =head4 C<save> - send current history to a file
 
@@ -3085,9 +3224,9 @@ Note that all C<^(save|source)>'s are commented out with a view to minimise recu
 =cut
 
                 # save source - write commands to a file for later use
-                $cmd =~ /^save\s*(.*)$/ && do {
-                    my $file = $1 || '.perl5dbrc';    # default?
-                    if ( open my $fh, "> $file" ) {
+                if (my ($new_fn) = $cmd =~ /\Asave\s*(.*)\z/) {
+                    my $filename = $new_fn || '.perl5dbrc';    # default?
+                    if ( open my $fh, '>', $filename ) {
 
                        # chomp to remove extraneous newlines from source'd files
                         chomp( my @truelist =
@@ -3097,14 +3236,14 @@ Note that all C<^(save|source)>'s are commented out with a view to minimise recu
                         print "commands saved in $file\n";
                     }
                     else {
-                        &warn("Can't save debugger commands in '$1': $!\n");
+                        &warn("Can't save debugger commands in '$new_fn': $!\n");
                     }
                     next CMD;
-                };
+                }
 
 =head4 C<R> - restart
 
-Restart the debugger session. 
+Restart the debugger session.
 
 =head4 C<rerun> - rerun the current session
 
@@ -3114,8 +3253,9 @@ Return to any given position in the B<true>-history list
 
                 # R - restart execution.
                 # rerun - controlled restart execution.
-                $cmd =~ /^(R|rerun\s*(.*))$/ && do {
-                    my @args = ($1 eq 'R' ? restart() : rerun($2));
+                if (my ($cmd_cmd, $cmd_params) =
+                    $cmd =~ /\A((?:R)|(?:rerun\s*(.*)))\z/) {
+                    my @args = ($cmd_cmd eq 'R' ? restart() : rerun($cmd_params));
 
                     # Close all non-system fds for a clean restart.  A more
                     # correct method would be to close all fds that were not
@@ -3140,14 +3280,14 @@ Return to any given position in the B<true>-history list
                     exec(@args) || print $OUT "exec failed: $!\n";
 
                     last CMD;
-                };
+                }
 
 =head4 C<|, ||> - pipe output through the pager.
 
 For C<|>, we save C<OUT> (the debugger's output filehandle) and C<STDOUT>
 (the program's standard output). For C<||>, we only save C<OUT>. We open a
 pipe to the pager (restoring the output filehandles if this fails). If this
-is the C<|> command, we also set up a C<SIGPIPE> handler which will simply 
+is the C<|> command, we also set up a C<SIGPIPE> handler which will simply
 set C<$signal>, sending us back into the debugger.
 
 We then trim off the pipe symbols and C<redo> the command loop at the
@@ -3157,7 +3297,7 @@ reading another.
 =cut
 
                 # || - run command in the pager, with output to DB::OUT.
-                $cmd =~ /^\|\|?\s*[^|]/ && do {
+                if ($cmd =~ m#\A\|\|?\s*[^|]#) {
                     if ( $pager =~ /^\|/ ) {
 
                         # Default pager is into a pipe. Redirect I/O.
@@ -3202,37 +3342,41 @@ reading another.
                       if $pager =~ /^\|/
                       && ( "" eq $SIG{PIPE} || "DEFAULT" eq $SIG{PIPE} );
 
-                    # Save current filehandle, unbuffer out, and put it back.
+                    OUT->autoflush(1);
+                    # Save current filehandle, and put it back.
                     $selected = select(OUT);
-                    $|        = 1;
-
                     # Don't put it back if pager was a pipe.
                     select($selected), $selected = "" unless $cmd =~ /^\|\|/;
 
                     # Trim off the pipe symbols and run the command now.
-                    $cmd =~ s/^\|+\s*//;
+                    $cmd =~ s#\A\|+\s*##;
                     redo PIPE;
-                };
+                }
 
 =head3 END OF COMMAND PARSING
 
-Anything left in C<$cmd> at this point is a Perl expression that we want to 
-evaluate. We'll always evaluate in the user's context, and fully qualify 
+Anything left in C<$cmd> at this point is a Perl expression that we want to
+evaluate. We'll always evaluate in the user's context, and fully qualify
 any variables we might want to address in the C<DB> package.
 
 =cut
 
                 # t - turn trace on.
-                $cmd =~ s/^t\s+(\d+)?/\$DB::trace |= 1;\n/ && do {
-                    $trace_to_depth = $1 ? $stack_depth||0 + $1 : 1E9;
-                };
+                if ($cmd =~ s#\At\s+(\d+)?#\$DB::trace |= 1;\n#) {
+                    my $trace_arg = $1;
+                    $trace_to_depth = $trace_arg ? $stack_depth||0 + $1 : 1E9;
+                }
 
                 # s - single-step. Remember the last command was 's'.
-                $cmd =~ s/^s\s/\$DB::single = 1;\n/ && do { $laststep = 's' };
+                if ($cmd =~ s/\As\s/\$DB::single = 1;\n/) {
+                    $laststep = 's';
+                }
 
                 # n - single-step, but not into subs. Remember last command
                 # was 'n'.
-                $cmd =~ s/^n\s/\$DB::single = 2;\n/ && do { $laststep = 'n' };
+                if ($cmd =~ s#\An\s#\$DB::single = 2;\n#) {
+                    $laststep = 'n';
+                }
 
             }    # PIPE:
 
@@ -3356,7 +3500,7 @@ again.
 
 =head2 sub
 
-C<sub> is called whenever a subroutine call happens in the program being 
+C<sub> is called whenever a subroutine call happens in the program being
 debugged. The variable C<$DB::sub> contains the name of the subroutine
 being called.
 
@@ -3370,7 +3514,7 @@ C<DB::sub> hadn't been there at all.
 
 C<sub> does all the work of printing the subroutine entry and exit messages
 enabled by setting C<$frame>. It notes what sub the autoloader got called for,
-and also prints the return value if needed (for the C<r> command and if 
+and also prints the return value if needed (for the C<r> command and if
 the 16 bit is set in C<$frame>).
 
 It also tracks the subroutine call depth by saving the current setting of
@@ -3434,7 +3578,11 @@ arguments with which the subroutine was invoked
 
 =cut
 
-sub sub {
+use vars qw($deep);
+
+# We need to fully qualify the name ("DB::sub") to make "use strict;"
+# happy. -- Shlomi Fish
+sub DB::sub {
        # Do not use a regex in this subroutine -> results in corrupted memory
        # See: [perl #66110]
 
@@ -3446,12 +3594,13 @@ sub sub {
     # return value in (if needed).
     my ( $al, $ret, @ret ) = "";
        if ($sub eq 'threads::new' && $ENV{PERL5DB_THREADED}) {
-               print "creating new thread\n"; 
+               print "creating new thread\n";
        }
 
     # If the last ten characters are '::AUTOLOAD', note we've traced
     # into AUTOLOAD for $sub.
     if ( length($sub) > 10 && substr( $sub, -10, 10 ) eq '::AUTOLOAD' ) {
+        no strict 'refs';
         $al = " for $$sub" if defined $$sub;
     }
 
@@ -3498,7 +3647,10 @@ sub sub {
         # Called in array context. call sub and capture output.
         # DB::DB will recursively get control again if appropriate; we'll come
         # back here when the sub is finished.
-       @ret = &$sub;
+        {
+            no strict 'refs';
+            @ret = &$sub;
+        }
 
         # Pop the single-step value back off the stack.
         $single |= $stack[ $stack_depth-- ];
@@ -3540,12 +3692,12 @@ sub sub {
     # Scalar context.
     else {
        if ( defined wantarray ) {
-
+        no strict 'refs';
            # Save the value if it's wanted at all.
            $ret = &$sub;
        }
        else {
-
+        no strict 'refs';
            # Void return, explicitly.
            &$sub;
            undef $ret;
@@ -3584,10 +3736,12 @@ sub sub {
         # Return the appropriate scalar value.
         $ret;
     } ## end else [ if (wantarray)
-} ## end sub sub
+} ## end sub _sub
 
 sub lsub : lvalue {
 
+    no strict 'refs';
+
        # lock ourselves under threads
        lock($DBGR);
 
@@ -3662,14 +3816,14 @@ In Perl 5.8.0, there was a major realignment of the commands and what they did,
 Most of the changes were to systematize the command structure and to eliminate
 commands that threw away user input without checking.
 
-The following sections describe the code added to make it easy to support 
-multiple command sets with conflicting command names. This section is a start 
+The following sections describe the code added to make it easy to support
+multiple command sets with conflicting command names. This section is a start
 at unifying all command processing to make it simpler to develop commands.
 
-Note that all the cmd_[a-zA-Z] subroutines require the command name, a line 
+Note that all the cmd_[a-zA-Z] subroutines require the command name, a line
 number, and C<$dbline> (the current line) as arguments.
 
-Support functions in this section which have multiple modes of failure C<die> 
+Support functions in this section which have multiple modes of failure C<die>
 on error; the rest simply return a false value.
 
 The user-interface functions (all of the C<cmd_*> functions) just output
@@ -3678,13 +3832,13 @@ error messages.
 =head2 C<%set>
 
 The C<%set> hash defines the mapping from command letter to subroutine
-name suffix. 
+name suffix.
 
 C<%set> is a two-level hash, indexed by set name and then by command name.
 Note that trying to set the CommandSet to C<foobar> simply results in the
 5.8.0 command set being used, since there's no top-level entry for C<foobar>.
 
-=cut 
+=cut
 
 ### The API section
 
@@ -3765,7 +3919,7 @@ sub _cancel_breakpoint_temp_enabled_status {
     my ($filename, $line) = @_;
 
     my $ref = _get_breakpoint_data_ref($filename, $line);
-    
+
     delete ($ref->{'temp_enabled'});
 
     if (! %$ref) {
@@ -3784,16 +3938,16 @@ sub _is_breakpoint_enabled {
 
 =head2 C<cmd_wrapper()> (API)
 
-C<cmd_wrapper()> allows the debugger to switch command sets 
-depending on the value of the C<CommandSet> option. 
+C<cmd_wrapper()> allows the debugger to switch command sets
+depending on the value of the C<CommandSet> option.
 
 It tries to look up the command in the C<%set> package-level I<lexical>
-(which means external entities can't fiddle with it) and create the name of 
-the sub to call based on the value found in the hash (if it's there). I<All> 
-of the commands to be handled in a set have to be added to C<%set>; if they 
+(which means external entities can't fiddle with it) and create the name of
+the sub to call based on the value found in the hash (if it's there). I<All>
+of the commands to be handled in a set have to be added to C<%set>; if they
 aren't found, the 5.8.0 equivalent is called (if there is one).
 
-This code uses symbolic references. 
+This code uses symbolic references.
 
 =cut
 
@@ -3810,14 +3964,14 @@ sub cmd_wrapper {
           || ( $cmd =~ /^[<>{]+/o ? 'prepost' : $cmd ) );
 
     # Call the command subroutine, call it by name.
-    return &$call( $cmd, $line, $dblineno );
+    return __PACKAGE__->can($call)->( $cmd, $line, $dblineno );
 } ## end sub cmd_wrapper
 
 =head3 C<cmd_a> (command)
 
 The C<a> command handles pre-execution actions. These are associated with a
-particular line, so they're stored in C<%dbline>. We default to the current 
-line if none is specified. 
+particular line, so they're stored in C<%dbline>. We default to the current
+line if none is specified.
 
 =cut
 
@@ -3851,6 +4005,8 @@ sub cmd_a {
 
                 # Add the action to the line.
                 $dbline{$lineno} .= "\0" . action($expr);
+
+                _set_breakpoint_enabled_status($filename, $lineno, 1);
             }
         } ## end if (length $expr)
     } ## end if ($line =~ /^\s*(\d*)\s*(\S.+)/)
@@ -3902,7 +4058,7 @@ sub cmd_A {
 =head3 C<delete_action> (API)
 
 C<delete_action> accepts either a line number or C<undef>. If a line number
-is specified, we check for the line being executable (if it's not, it 
+is specified, we check for the line being executable (if it's not, it
 couldn't have had an  action). If it is, we just take the action off (this
 will get any kind of an action, including breakpoints).
 
@@ -3923,9 +4079,9 @@ sub delete_action {
         print $OUT "Deleting all actions...\n";
         for my $file ( keys %had_breakpoints ) {
             local *dbline = $main::{ '_<' . $file };
-            my $max = $#dbline;
+            $max = $#dbline;
             my $was;
-            for ( $i = 1 ; $i <= $max ; $i++ ) {
+            for $i (1 .. $max) {
                 if ( defined $dbline{$i} ) {
                     $dbline{$i} =~ s/\0[^\0]*//;
                     delete $dbline{$i} if $dbline{$i} eq '';
@@ -3933,7 +4089,7 @@ sub delete_action {
                 unless ( $had_breakpoints{$file} &= ~2 ) {
                     delete $had_breakpoints{$file};
                 }
-            } ## end for ($i = 1 ; $i <= $max...
+            } ## end for ($i = 1 .. $max)
         } ## end for my $file (keys %had_breakpoints)
     } ## end else [ if (defined($i))
 } ## end sub delete_action
@@ -3984,7 +4140,7 @@ sub cmd_b {
         $subname =~ s/\'/::/g;
 
         # Qualify it into the current package unless it's already qualified.
-        $subname = "${'package'}::" . $subname unless $subname =~ /::/;
+        $subname = "${package}::" . $subname unless $subname =~ /::/;
 
         # Add main if it starts with ::.
         $subname = "main" . $subname if substr( $subname, 0, 2 ) eq "::";
@@ -3997,7 +4153,7 @@ sub cmd_b {
         my ($filename, $line_num, $cond) = ($1, $2, $3);
         cmd_b_filename_line(
             $filename,
-            $line_num, 
+            $line_num,
             (length($cond) ? $cond : '1'),
         );
     }
@@ -4006,7 +4162,7 @@ sub cmd_b {
 
         #
         $subname = $1;
-        $cond = length $2 ? $2 : '1';
+        my $cond = length $2 ? $2 : '1';
         &cmd_b_sub( $subname, $cond );
     }
 
@@ -4017,7 +4173,7 @@ sub cmd_b {
         $line = $1 || $dbline;
 
         # If there's no condition, make it '1'.
-        $cond = length $2 ? $2 : '1';
+        my $cond = length $2 ? $2 : '1';
 
         # Break on line.
         &cmd_b_line( $line, $cond );
@@ -4032,7 +4188,7 @@ sub cmd_b {
 =head3 C<break_on_load> (API)
 
 We want to break when this file is loaded. Mark this file in the
-C<%break_on_load> hash, and note that it has a breakpoint in 
+C<%break_on_load> hash, and note that it has a breakpoint in
 C<%had_breakpoints>.
 
 =cut
@@ -4045,7 +4201,7 @@ sub break_on_load {
 
 =head3 C<report_break_on_load> (API)
 
-Gives us an array of filenames that are set to break on load. Note that 
+Gives us an array of filenames that are set to break on load. Note that
 only files with break-on-load are in here, so simply showing the keys
 suffices.
 
@@ -4058,7 +4214,7 @@ sub report_break_on_load {
 =head3 C<cmd_b_load> (command)
 
 We take the file passed in and try to find it in C<%INC> (which maps modules
-to files they came from). We mark those files for break-on-load via 
+to files they came from). We mark those files for break-on-load via
 C<break_on_load> and then report that it was done.
 
 =cut
@@ -4096,7 +4252,7 @@ sub cmd_b_load {
 
 Several of the functions we need to implement in the API need to work both
 on the current file and on other files. We don't want to duplicate code, so
-C<$filename_error> is used to contain the name of the file that's being 
+C<$filename_error> is used to contain the name of the file that's being
 worked on (if it's not the current one).
 
 We can now build functions in pairs: the basic function works on the current
@@ -4106,7 +4262,7 @@ current file.
 
 The second function is a wrapper which does the following:
 
-=over 4 
+=over 4
 
 =item *
 
@@ -4114,11 +4270,11 @@ Localizes C<$filename_error> and sets it to the name of the file to be processed
 
 =item *
 
-Localizes the C<*dbline> glob and reassigns it to point to the file we want to process. 
+Localizes the C<*dbline> glob and reassigns it to point to the file we want to process.
 
 =item *
 
-Calls the first function. 
+Calls the first function.
 
 The first function works on the I<current> file (i.e., the one we changed to),
 and prints C<$filename_error> in the error message (the name of the other file)
@@ -4134,6 +4290,7 @@ details.
 
 =cut
 
+use vars qw($filename_error);
 $filename_error = '';
 
 =head3 breakable_line(from, to) (API)
@@ -4142,7 +4299,7 @@ The subroutine decides whether or not a line in the current file is breakable.
 It walks through C<@dbline> within the range of lines specified, looking for
 the first line that is breakable.
 
-If C<$to> is greater than C<$from>, the search moves forwards, finding the 
+If C<$to> is greater than C<$from>, the search moves forwards, finding the
 first line I<after> C<$to> that's breakable, if there is one.
 
 If C<$from> is greater than C<$to>, the search goes I<backwards>, finding the
@@ -4245,7 +4402,7 @@ sub breakable_line_in_filename {
 
 =head3 break_on_line(lineno, [condition]) (API)
 
-Adds a breakpoint with the specified condition (or 1 if no condition was 
+Adds a breakpoint with the specified condition (or 1 if no condition was
 specified) to the specified line. Dies if it can't.
 
 =cut
@@ -4284,35 +4441,39 @@ sub break_on_line {
 
 =head3 cmd_b_line(line, [condition]) (command)
 
-Wrapper for C<break_on_line>. Prints the failure message if it 
+Wrapper for C<break_on_line>. Prints the failure message if it
 doesn't work.
 
-=cut 
+=cut
 
 sub cmd_b_line {
-    eval { break_on_line(@_); 1 } or do {
+    if (not eval { break_on_line(@_); 1 }) {
         local $\ = '';
         print $OUT $@ and return;
-    };
+    }
+
+    return;
 } ## end sub cmd_b_line
 
 =head3 cmd_b_filename_line(line, [condition]) (command)
 
-Wrapper for C<break_on_filename_line>. Prints the failure message if it 
+Wrapper for C<break_on_filename_line>. Prints the failure message if it
 doesn't work.
 
-=cut 
+=cut
 
 sub cmd_b_filename_line {
-    eval { break_on_filename_line(@_); 1 } or do {
+    if (not eval { break_on_filename_line(@_); 1 }) {
         local $\ = '';
         print $OUT $@ and return;
-    };
+    }
+
+    return;
 }
 
 =head3 break_on_filename_line(file, line, [condition]) (API)
 
-Switches to the file specified and then calls C<break_on_line> to set 
+Switches to the file specified and then calls C<break_on_line> to set
 the breakpoint.
 
 =cut
@@ -4336,7 +4497,7 @@ sub break_on_filename_line {
 
 =head3 break_on_filename_line_range(file, from, to, [condition]) (API)
 
-Switch to another file, search the range of lines specified for an 
+Switch to another file, search the range of lines specified for an
 executable one, and put a breakpoint on the first one you find.
 
 =cut
@@ -4373,7 +4534,7 @@ sub subroutine_filename_lines {
 =head3 break_subroutine(subname) (API)
 
 Places a break on the first line possible in the specified subroutine. Uses
-C<subroutine_filename_lines> to find the subroutine, and 
+C<subroutine_filename_lines> to find the subroutine, and
 C<break_on_filename_line_range> to place the break.
 
 =cut
@@ -4385,12 +4546,13 @@ sub break_subroutine {
     my ( $file, $s, $e ) = subroutine_filename_lines($subname)
       or die "Subroutine $subname not found.\n";
 
+
     # Null condition changes to '1' (always true).
-    $cond = 1 unless @_ >= 2;
+    my $cond = @_ ? shift(@_) : 1;
 
     # Put a break the first place possible in the range of lines
     # that make up this subroutine.
-    break_on_filename_line_range( $file, $s, $e, @_ );
+    break_on_filename_line_range( $file, $s, $e, $cond );
 } ## end sub break_subroutine
 
 =head3 cmd_b_sub(subname, [condition]) (command)
@@ -4399,7 +4561,7 @@ We take the incoming subroutine name and fully-qualify it as best we can.
 
 =over 4
 
-=item 1. If it's already fully-qualified, leave it alone. 
+=item 1. If it's already fully-qualified, leave it alone.
 
 =item 2. Try putting it in the current package.
 
@@ -4409,7 +4571,7 @@ We take the incoming subroutine name and fully-qualify it as best we can.
 
 =back
 
-After all this cleanup, we call C<break_subroutine> to try to set the 
+After all this cleanup, we call C<break_subroutine> to try to set the
 breakpoint.
 
 =cut
@@ -4429,7 +4591,7 @@ sub cmd_b_sub {
         my $s = $subname;
 
         # Put it in this package unless it's already qualified.
-        $subname = "${'package'}::" . $subname
+        $subname = "${package}::" . $subname
           unless $subname =~ /::/;
 
         # Requalify it into CORE::GLOBAL if qualifying it into this
@@ -4446,10 +4608,12 @@ sub cmd_b_sub {
     } ## end unless (ref $subname eq 'CODE')
 
     # Try to set the breakpoint.
-    eval { break_subroutine( $subname, $cond ); 1 } or do {
+    if (not eval { break_subroutine( $subname, $cond ); 1 }) {
         local $\ = '';
         print $OUT $@ and return;
-      }
+    }
+
+    return;
 } ## end sub cmd_b_sub
 
 =head3 C<cmd_B> - delete breakpoint(s) (command)
@@ -4481,10 +4645,10 @@ sub cmd_B {
 
     # If there is a line spec, delete the breakpoint on that line.
     elsif ( $line =~ /^(\S.*)/ ) {
-        eval { &delete_breakpoint( $line || $dbline ); 1 } or do {
+        if (not eval { &delete_breakpoint( $line || $dbline ); 1 }) {
             local $\ = '';
             print $OUT $@ and return;
-        };
+        }
     } ## end elsif ($line =~ /^(\S.*)/)
 
     # No line spec.
@@ -4506,14 +4670,14 @@ part of the 'condition\0action' that says there's a breakpoint here. If,
 after we've done that, there's nothing left, we delete the corresponding
 line in C<%dbline> to signal that no action needs to be taken for this line.
 
-For all breakpoints, we iterate through the keys of C<%had_breakpoints>, 
+For all breakpoints, we iterate through the keys of C<%had_breakpoints>,
 which lists all currently-loaded files which have breakpoints. We then look
 at each line in each of these files, temporarily switching the C<%dbline>
 and C<@dbline> structures to point to the files in question, and do what
 we did in the single line case: delete the condition in C<@dbline>, and
 delete the key in C<%dbline> if nothing's left.
 
-We then wholesale delete C<%postponed>, C<%postponed_file>, and 
+We then wholesale delete C<%postponed>, C<%postponed_file>, and
 C<%break_on_load>, because these structures contain breakpoints for files
 and code that haven't been loaded yet. We can just kill these off because there
 are no magical debugger structures associated with them.
@@ -4552,11 +4716,11 @@ sub delete_breakpoint {
             # Switch to the desired file temporarily.
             local *dbline = $main::{ '_<' . $file };
 
-            my $max = $#dbline;
+            $max = $#dbline;
             my $was;
 
             # For all lines in this file ...
-            for ( $i = 1 ; $i <= $max ; $i++ ) {
+            for $i (1 .. $max) {
 
                 # If there's a breakpoint or action on this line ...
                 if ( defined $dbline{$i} ) {
@@ -4570,7 +4734,7 @@ sub delete_breakpoint {
                         _delete_breakpoint_data_ref($file, $i);
                     }
                 } ## end if (defined $dbline{$i...
-            } ## end for ($i = 1 ; $i <= $max...
+            } ## end for $i (1 .. $max)
 
             # If, after we turn off the "there were breakpoints in this file"
             # bit, the entry in %had_breakpoints for this file is zero,
@@ -4636,14 +4800,14 @@ This could be used (when implemented) to send commands to all threads (E cmd).
 sub cmd_E {
     my $cmd  = shift;
     my $line = shift;
-       unless (exists($INC{'threads.pm'})) { 
+       unless (exists($INC{'threads.pm'})) {
                print "threads not loaded($ENV{PERL5DB_THREADED})
                please run the debugger with PERL5DB_THREADED=1 set in the environment\n";
        } else {
                my $tid = threads->tid;
-               print "thread ids: ".join(', ', 
+               print "thread ids: ".join(', ',
                        map { ($tid == $_->tid ? '<'.$_->tid.'>' : $_->tid) } threads->list
-               )."\n"; 
+               )."\n";
        }
 } ## end sub cmd_E
 
@@ -4665,6 +4829,9 @@ Showing help for a specific command
 
 =cut
 
+use vars qw($help);
+use vars qw($summary);
+
 sub cmd_h {
     my $cmd = shift;
 
@@ -4672,18 +4839,15 @@ sub cmd_h {
     my $line = shift || '';
 
     # 'h h'. Print the long-format help.
-    if ( $line =~ /^h\s*/ ) {
+    if ( $line =~ /\Ah\s*\z/ ) {
         print_help($help);
     }
 
     # 'h <something>'. Search for the command and print only its help.
-    elsif ( $line =~ /^(\S.*)$/ ) {
+    elsif ( my ($asked) = $line =~ /\A(\S.*)\z/ ) {
 
         # support long commands; otherwise bogus errors
         # happen when you ask for h on <CR> for example
-        my $asked = $1;    # the command requested
-                           # (for proper error message)
-
         my $qasked = quotemeta($asked);    # for searching; we don't
                                            # want to use it as a pattern.
                                            # XXX: finds CR but not <CR>
@@ -4706,7 +4870,7 @@ sub cmd_h {
                                  $qasked     # The command
                                  ([\s\S]*?)  # Description line(s)
                               \n)            # End of last description line
-                              (?!\s)         # Next line not starting with 
+                              (?!\s)         # Next line not starting with
                                              # whitespace
                              /mgx
               )
@@ -4758,10 +4922,10 @@ sub cmd_i {
 
 Most of the command is taken up with transforming all the different line
 specification syntaxes into 'start-stop'. After that is done, the command
-runs a loop over C<@dbline> for the specified range of lines. It handles 
+runs a loop over C<@dbline> for the specified range of lines. It handles
 the printing of each line and any markers (C<==E<gt>> for current line,
 C<b> for break on this line, C<a> for action on this line, C<:> for this
-line breakable). 
+line breakable).
 
 We save the last line listed in the C<$start> global for further listing
 later.
@@ -4786,20 +4950,23 @@ sub cmd_l {
         my ($s) = &eval;
 
         # Ooops. Bad scalar.
-        print( $OUT "Error: $@\n" ), next CMD if $@;
+        if ($@) {
+            print {$OUT} "Error: $@\n";
+            next CMD;
+        }
 
         # Good scalar. If it's a reference, find what it points to.
         $s = CvGV_name($s);
-        print( $OUT "Interpreted as: $1 $s\n" );
+        print {$OUT} "Interpreted as: $1 $s\n";
         $line = "$1 $s";
 
         # Call self recursively to really do the command.
-        &cmd_l( 'l', $s );
+        cmd_l( 'l', $s );
     } ## end if ($line =~ /^(\$.*)/s)
 
     # l name. Try to find a sub by that name.
-    elsif ( $line =~ /^([\':A-Za-z_][\':\w]*(\[.*\])?)/s ) {
-        my $s = $subname = $1;
+    elsif ( ($subname) = $line =~ /\A([\':A-Za-z_][\':\w]*(?:\[.*\])?)/s ) {
+        my $s = $subname;
 
         # De-Perl4.
         $subname =~ s/\'/::/;
@@ -4819,10 +4986,10 @@ sub cmd_l {
 
         # Get name:start-stop from find_sub, and break this up at
         # colons.
-        @pieces = split( /:/, find_sub($subname) || $sub{$subname} );
+        my @pieces = split( /:/, find_sub($subname) || $sub{$subname} );
 
         # Pull off start-stop.
-        $subrange = pop @pieces;
+        my $subrange = pop @pieces;
 
         # If the name contained colons, the split broke it up.
         # Put it back together.
@@ -4848,7 +5015,7 @@ sub cmd_l {
 
             # Call self recursively to list the range.
             $line = $subrange;
-            &cmd_l( 'l', $subrange );
+            cmd_l( 'l', $subrange );
         } ## end if ($subrange)
 
         # Couldn't find it.
@@ -4858,43 +5025,43 @@ sub cmd_l {
     } ## end elsif ($line =~ /^([\':A-Za-z_][\':\w]*(\[.*\])?)/s)
 
     # Bare 'l' command.
-    elsif ( $line =~ /^\s*$/ ) {
+    elsif ( $line !~ /\S/ ) {
 
         # Compute new range to list.
         $incr = $window - 1;
         $line = $start . '-' . ( $start + $incr );
 
         # Recurse to do it.
-        &cmd_l( 'l', $line );
+        cmd_l( 'l', $line );
     }
 
     # l [start]+number_of_lines
-    elsif ( $line =~ /^(\d*)\+(\d*)$/ ) {
+    elsif ( my ($new_start, $new_incr) = $line =~ /\A(\d*)\+(\d*)\z/ ) {
 
         # Don't reset start for 'l +nnn'.
-        $start = $1 if $1;
+        $start = $new_start if $new_start;
 
         # Increment for list. Use window size if not specified.
         # (Allows 'l +' to work.)
-        $incr = $2;
+        $incr = $new_incr;
         $incr = $window - 1 unless $incr;
 
         # Create a line range we'll understand, and recurse to do it.
         $line = $start . '-' . ( $start + $incr );
-        &cmd_l( 'l', $line );
+        cmd_l( 'l', $line );
     } ## end elsif ($line =~ /^(\d*)\+(\d*)$/)
 
     # l start-stop or l start,stop
     elsif ( $line =~ /^((-?[\d\$\.]+)([-,]([\d\$\.]+))?)?/ ) {
 
         # Determine end point; use end of file if not specified.
-        $end = ( !defined $2 ) ? $max : ( $4 ? $4 : $2 );
+        my $end = ( !defined $2 ) ? $max : ( $4 ? $4 : $2 );
 
         # Go on to the end, and then stop.
         $end = $max if $end > $max;
 
         # Determine start line.
-        $i    = $2;
+        my $i    = $2;
         $i    = $line if $i eq '.';
         $i    = 1 if $i < 1;
         $incr = $end - $i;
@@ -4921,7 +5088,7 @@ sub cmd_l {
 
                 # ==> if this is the current line in execution,
                 # : if it's breakable.
-                $arrow =
+                my $arrow =
                   ( $i == $current_line and $filename eq $filename_ini )
                   ? '==>'
                   : ( $dbline[$i] + 0 ? ':' : ' ' );
@@ -4953,11 +5120,11 @@ sub cmd_l {
 
 To list breakpoints, the command has to look determine where all of them are
 first. It starts a C<%had_breakpoints>, which tells us what all files have
-breakpoints and/or actions. For each file, we switch the C<*dbline> glob (the 
-magic source and breakpoint data structures) to the file, and then look 
-through C<%dbline> for lines with breakpoints and/or actions, listing them 
-out. We look through C<%postponed> not-yet-compiled subroutines that have 
-breakpoints, and through C<%postponed_file> for not-yet-C<require>'d files 
+breakpoints and/or actions. For each file, we switch the C<*dbline> glob (the
+magic source and breakpoint data structures) to the file, and then look
+through C<%dbline> for lines with breakpoints and/or actions, listing them
+out. We look through C<%postponed> not-yet-compiled subroutines that have
+breakpoints, and through C<%postponed_file> for not-yet-C<require>'d files
 that have breakpoints.
 
 Watchpoints are simpler: we just list the entries in C<@to_watch>.
@@ -4988,12 +5155,12 @@ sub cmd_L {
             local *dbline = $main::{ '_<' . $file };
 
             # Set up to look through the whole file.
-            my $max = $#dbline;
+            $max = $#dbline;
             my $was;    # Flag: did we print something
                         # in this file?
 
             # For each line in the file ...
-            for ( $i = 1 ; $i <= $max ; $i++ ) {
+            for my $i (1 .. $max) {
 
                 # We've got something on this line.
                 if ( defined $dbline{$i} ) {
@@ -5005,7 +5172,7 @@ sub cmd_L {
                     print $OUT " $i:\t", $dbline[$i];
 
                     # Pull out the condition and the action.
-                    ( $stop, $action ) = split( /\0/, $dbline{$i} );
+                    my ( $stop, $action ) = split( /\0/, $dbline{$i} );
 
                     # Print the break if there is one and it's wanted.
                     print $OUT "   break if (", $stop, ")\n"
@@ -5020,7 +5187,7 @@ sub cmd_L {
                     # Quit if the user hit interrupt.
                     last if $signal;
                 } ## end if (defined $dbline{$i...
-            } ## end for ($i = 1 ; $i <= $max...
+            } ## end for my $i (1 .. $max)
         } ## end for my $file (keys %had_breakpoints)
     } ## end if ($break_wanted or $action_wanted)
 
@@ -5042,12 +5209,10 @@ sub cmd_L {
     # If there are any, list them.
     if ( @have and ( $break_wanted or $action_wanted ) ) {
         print $OUT "Postponed breakpoints in files:\n";
-        my ( $file, $line );
-
-        for $file ( keys %postponed_file ) {
+        for my $file ( keys %postponed_file ) {
             my $db = $postponed_file{$file};
             print $OUT " $file:\n";
-            for $line ( sort { $a <=> $b } keys %$db ) {
+            for my $line ( sort { $a <=> $b } keys %$db ) {
                 print $OUT "  $line:\n";
                 my ( $stop, $action ) = split( /\0/, $$db{$line} );
                 print $OUT "    break if (", $stop, ")\n"
@@ -5062,22 +5227,19 @@ sub cmd_L {
         } ## end for $file (keys %postponed_file)
     } ## end if (@have and ($break_wanted...
     if ( %break_on_load and $break_wanted ) {
-        print $OUT "Breakpoints on load:\n";
-        my $file;
-        for $file ( keys %break_on_load ) {
-            print $OUT " $file\n";
-            last if $signal;
+        print {$OUT} "Breakpoints on load:\n";
+        BREAK_ON_LOAD: for my $filename ( keys %break_on_load ) {
+            print {$OUT} " $filename\n";
+            last BREAK_ON_LOAD if $signal;
         }
     } ## end if (%break_on_load and...
-    if ($watch_wanted) {
-        if ( $trace & 2 ) {
-            print $OUT "Watch-expressions:\n" if @to_watch;
-            for my $expr (@to_watch) {
-                print $OUT " $expr\n";
-                last if $signal;
-            }
-        } ## end if ($trace & 2)
-    } ## end if ($watch_wanted)
+    if ($watch_wanted and ( $trace & 2 )) {
+        print {$OUT} "Watch-expressions:\n" if @to_watch;
+        TO_WATCH: for my $expr (@to_watch) {
+            print {$OUT} " $expr\n";
+            last TO_WATCH if $signal;
+        }
+    }
 } ## end sub cmd_L
 
 =head3 C<cmd_M> - list modules (command)
@@ -5092,7 +5254,7 @@ sub cmd_M {
 
 =head3 C<cmd_o> - options (command)
 
-If this is just C<o> by itself, we list the current settings via 
+If this is just C<o> by itself, we list the current settings via
 C<dump_option>. If there's a nonblank value following it, we pass that on to
 C<parse_options> for processing.
 
@@ -5133,7 +5295,9 @@ Uses the C<$preview> variable set in the second C<BEGIN> block (q.v.) to
 move back a few lines to list the selected line in context. Uses C<cmd_l>
 to do the actual listing after figuring out the range of line to request.
 
-=cut 
+=cut
+
+use vars qw($preview);
 
 sub cmd_v {
     my $cmd  = shift;
@@ -5158,7 +5322,7 @@ sub cmd_v {
         $line = $start . '-' . ( $start + $incr );
 
         # List the lines.
-        &cmd_l( 'l', $line );
+        cmd_l( 'l', $line );
     } ## end if ($line =~ /^(\d*)$/)
 } ## end sub cmd_v
 
@@ -5211,13 +5375,13 @@ sub cmd_w {
 This command accepts either a watch expression to be removed from the list
 of watch expressions, or C<*> to delete them all.
 
-If C<*> is specified, we simply empty the watch expression list and the 
-watch expression value list. We also turn off the bit that says we've got 
+If C<*> is specified, we simply empty the watch expression list and the
+watch expression value list. We also turn off the bit that says we've got
 watch expressions.
 
 If an expression (or partial expression) is specified, we pattern-match
 through the expressions and remove the ones that match. We also discard
-the corresponding values. If no watch expressions are left, we turn off 
+the corresponding values. If no watch expressions are left, we turn off
 the I<watching expressions> bit.
 
 =cut
@@ -5281,7 +5445,7 @@ throughout the debugger.
 =head2 save
 
 save() saves the user's versions of globals that would mess us up in C<@saved>,
-and installs the versions we like better. 
+and installs the versions we like better.
 
 =cut
 
@@ -5302,7 +5466,7 @@ sub save {
 
 print_lineinfo prints whatever it is that it is handed; it prints it to the
 C<$LINEINFO> filehandle instead of just printing it to STDOUT. This allows
-us to feed line information to a slave editor without messing up the 
+us to feed line information to a slave editor without messing up the
 debugger output.
 
 =cut
@@ -5321,11 +5485,11 @@ sub print_lineinfo {
 Handles setting postponed breakpoints in subroutines once they're compiled.
 For breakpoints, we use C<DB::find_sub> to locate the source file and line
 range for the subroutine, then mark the file as having a breakpoint,
-temporarily switch the C<*dbline> glob over to the source file, and then 
+temporarily switch the C<*dbline> glob over to the source file, and then
 search the given range of lines to find a breakable line. If we find one,
 we set the breakpoint on it, deleting the breakpoint from C<%postponed>.
 
-=cut 
+=cut
 
 # The following takes its argument via $evalarg to preserve current @_
 
@@ -5359,7 +5523,7 @@ sub postponed_sub {
             $had_breakpoints{$file} |= 1;
 
             # Last line in file.
-            my $max = $#dbline;
+            $max = $#dbline;
 
             # Search forward until we hit a breakable line or get to
             # the end of the file.
@@ -5384,11 +5548,11 @@ sub postponed_sub {
 =head2 C<postponed>
 
 Called after each required file is compiled, but before it is executed;
-also called if the name of a just-compiled subroutine is a key of 
+also called if the name of a just-compiled subroutine is a key of
 C<%postponed>. Propagates saved breakpoints (from C<b compile>, C<b load>,
 etc.) into the just-compiled code.
 
-If this is a C<require>'d file, the incoming parameter is the glob 
+If this is a C<require>'d file, the incoming parameter is the glob
 C<*{"_<$filename"}>, with C<$filename> the name of the C<require>'d file.
 
 If it's a subroutine, the incoming parameter is the subroutine name.
@@ -5447,36 +5611,36 @@ sub postponed {
 
 =head2 C<dumpit>
 
-C<dumpit> is the debugger's wrapper around dumpvar.pl. 
+C<dumpit> is the debugger's wrapper around dumpvar.pl.
 
 It gets a filehandle (to which C<dumpvar.pl>'s output will be directed) and
-a reference to a variable (the thing to be dumped) as its input. 
+a reference to a variable (the thing to be dumped) as its input.
 
 The incoming filehandle is selected for output (C<dumpvar.pl> is printing to
 the currently-selected filehandle, thank you very much). The current
-values of the package globals C<$single> and C<$trace> are backed up in 
+values of the package globals C<$single> and C<$trace> are backed up in
 lexicals, and they are turned off (this keeps the debugger from trying
 to single-step through C<dumpvar.pl> (I think.)). C<$frame> is localized to
 preserve its current value and it is set to zero to prevent entry/exit
-messages from printing, and C<$doret> is localized as well and set to -2 to 
+messages from printing, and C<$doret> is localized as well and set to -2 to
 prevent return values from being shown.
 
-C<dumpit()> then checks to see if it needs to load C<dumpvar.pl> and 
-tries to load it (note: if you have a C<dumpvar.pl>  ahead of the 
-installed version in C<@INC>, yours will be used instead. Possible security 
+C<dumpit()> then checks to see if it needs to load C<dumpvar.pl> and
+tries to load it (note: if you have a C<dumpvar.pl>  ahead of the
+installed version in C<@INC>, yours will be used instead. Possible security
 problem?).
 
 It then checks to see if the subroutine C<main::dumpValue> is now defined
-(it should have been defined by C<dumpvar.pl>). If it has, C<dumpit()> 
+it should have been defined by C<dumpvar.pl>). If it has, C<dumpit()>
 localizes the globals necessary for things to be sane when C<main::dumpValue()>
-is called, and picks up the variable to be dumped from the parameter list. 
+is called, and picks up the variable to be dumped from the parameter list.
 
-It checks the package global C<%options> to see if there's a C<dumpDepth> 
-specified. If not, -1 is assumed; if so, the supplied value gets passed on to 
-C<dumpvar.pl>. This tells C<dumpvar.pl> where to leave off when dumping a 
+It checks the package global C<%options> to see if there's a C<dumpDepth>
+specified. If not, -1 is assumed; if so, the supplied value gets passed on to
+C<dumpvar.pl>. This tells C<dumpvar.pl> where to leave off when dumping a
 structure: -1 means dump everything.
 
-C<dumpValue()> is then called if possible; if not, C<dumpit()>just prints a 
+C<dumpValue()> is then called if possible; if not, C<dumpit()>just prints a
 warning.
 
 In either case, C<$single>, C<$trace>, C<$frame>, and C<$doret> are restored
@@ -5488,7 +5652,7 @@ sub dumpit {
 
     # Save the current output filehandle and switch to the one
     # passed in as the first parameter.
-    local ($savout) = select(shift);
+    my $savout = select(shift);
 
     # Save current settings of $single and $trace, and then turn them off.
     my $osingle = $single;
@@ -5532,7 +5696,7 @@ sub dumpit {
 
 =head2 C<print_trace>
 
-C<print_trace>'s job is to print a stack trace. It does this via the 
+C<print_trace>'s job is to print a stack trace. It does this via the
 C<dump_trace> routine, which actually does all the ferreting-out of the
 stack trace data. C<print_trace> takes care of formatting it nicely and
 printing it to the proper filehandle.
@@ -5586,7 +5750,7 @@ sub print_trace {
 
     # Run through the traceback info, format it, and print it.
     my $s;
-    for ( $i = 0 ; $i <= $#sub ; $i++ ) {
+    for my $i (0 .. $#sub) {
 
         # Drop out if the user has lost interest and hit control-C.
         last if $signal;
@@ -5626,7 +5790,7 @@ sub print_trace {
               . " called from $file"
               . " line $sub[$i]{line}\n";
         }
-    } ## end for ($i = 0 ; $i <= $#sub...
+    } ## end for my $i (0 .. $#sub)
 } ## end sub print_trace
 
 =head2 dump_trace(skip[,count])
@@ -5636,7 +5800,7 @@ some filtering and cleanup of the data, but mostly it just collects it to
 make C<print_trace()>'s job easier.
 
 C<skip> defines the number of stack frames to be skipped, working backwards
-from the most current. C<count> determines the total number of frames to 
+from the most current. C<count> determines the total number of frames to
 be returned; all of them (well, the first 10^9) are returned if C<count>
 is omitted.
 
@@ -5695,16 +5859,16 @@ sub dump_trace {
     # quit.
     # Up the stack frame index to go back one more level each time.
     for (
-        $i = $skip ;
+        my $i = $skip ;
         $i < $count
         and ( $p, $file, $line, $sub, $h, $context, $e, $r ) = caller($i) ;
         $i++
-      )
+    )
     {
 
         # Go through the arguments and save them for later.
         @a = ();
-        for $arg (@args) {
+        for my $arg (@args) {
             my $type;
             if ( not defined $arg ) {    # undefined parameter
                 push @a, "undef";
@@ -5821,15 +5985,17 @@ to check that the thing it's being matched against has properly-matched
 curly braces.
 
 Of note is the definition of the C<$balanced_brace_re> global via C<||=>, which
-speeds things up by only creating the qr//'ed expression once; if it's 
+speeds things up by only creating the qr//'ed expression once; if it's
 already defined, we don't try to define it again. A speed hack.
 
 =cut
 
+use vars qw($balanced_brace_re);
+
 sub unbalanced {
 
     # I hate using globals!
-    $balanced_brace_re ||= qr{ 
+    $balanced_brace_re ||= qr{
         ^ \{
              (?:
                  (?> [^{}] + )              # Non-parens without backtracking
@@ -5856,8 +6022,8 @@ sub gets {
 =head2 C<DB::system()> - handle calls to<system()> without messing up the debugger
 
 The C<system()> function assumes that it can just go ahead and use STDIN and
-STDOUT, but under the debugger, we want it to use the debugger's input and 
-outout filehandles. 
+STDOUT, but under the debugger, we want it to use the debugger's input and
+outout filehandles.
 
 C<DB::system()> socks away the program's STDIN and STDOUT, and then substitutes
 the debugger's IN and OUT filehandles for them. It does the C<system()> call,
@@ -5909,15 +6075,18 @@ by the debugger.
 
 If the C<noTTY> debugger option was set, we'll either use the terminal
 supplied (the value of the C<noTTY> option), or we'll use C<Term::Rendezvous>
-to find one. If we're a forked debugger, we call C<resetterm> to try to 
-get a whole new terminal if we can. 
+to find one. If we're a forked debugger, we call C<resetterm> to try to
+get a whole new terminal if we can.
 
 In either case, we set up the terminal next. If the C<ReadLine> option was
 true, we'll get a C<Term::ReadLine> object for the current terminal and save
-the appropriate attributes. We then 
+the appropriate attributes. We then
 
 =cut
 
+use vars qw($ornaments);
+use vars qw($rl_attribs);
+
 sub setterm {
 
     # Load Term::Readline, but quietly; don't debug it and don't trace it.
@@ -5934,9 +6103,7 @@ sub setterm {
             open( OUT, ">$o" ) or die "Cannot open TTY '$o' for write: $!";
             $IN  = \*IN;
             $OUT = \*OUT;
-            my $sel = select($OUT);
-            $| = 1;
-            select($sel);
+            $OUT->autoflush(1);
         } ## end if ($tty)
 
         # We don't have a TTY - try to find one via Term::Rendezvous.
@@ -6031,8 +6198,8 @@ C<IN> and C<OUT> filehandle for the new debugger. Otherwise, the two processes
 fight over the terminal, and you can never quite be sure who's going to get the
 input you're typing.
 
-C<get_fork_TTY> is a glob-aliased function which calls the real function that 
-is tasked with doing all the necessary operating system mojo to get a new 
+C<get_fork_TTY> is a glob-aliased function which calls the real function that
+is tasked with doing all the necessary operating system mojo to get a new
 TTY (and probably another window) and to direct the new debugger to read and
 write there.
 
@@ -6043,7 +6210,7 @@ work for I<your> platform and contribute them.
 
 =head3 C<socket_get_fork_TTY>
 
-=cut 
+=cut
 
 sub connect_remoteport {
     require IO::Socket;
@@ -6070,18 +6237,18 @@ sub socket_get_fork_TTY {
 
 =head3 C<xterm_get_fork_TTY>
 
-This function provides the C<get_fork_TTY> function for X11. If a 
+This function provides the C<get_fork_TTY> function for X11. If a
 program running under the debugger forks, a new <xterm> window is opened and
 the subsidiary debugger is directed there.
 
 The C<open()> call is of particular note here. We have the new C<xterm>
-we're spawning route file number 3 to STDOUT, and then execute the C<tty> 
-command (which prints the device name of the TTY we'll want to use for input 
+we're spawning route file number 3 to STDOUT, and then execute the C<tty>
+command (which prints the device name of the TTY we'll want to use for input
 and output to STDOUT, then C<sleep> for a very long time, routing this output
 to file number 3. This way we can simply read from the <XT> filehandle (which
-is STDOUT from the I<commands> we ran) to get the TTY we want to use. 
+is STDOUT from the I<commands> we ran) to get the TTY we want to use.
 
-Only works if C<xterm> is in your path and C<$ENV{DISPLAY}>, etc. are 
+Only works if C<xterm> is in your path and C<$ENV{DISPLAY}>, etc. are
 properly set up.
 
 =cut
@@ -6240,6 +6407,8 @@ Flags are:
 
 =cut
 
+use vars qw($fork_TTY);
+
 sub create_IN_OUT {    # Create a window with IN/OUT handles redirected there
 
     # If we know how to get a new TTY, do it! $in will have
@@ -6292,13 +6461,13 @@ EOP
 
 Handles rejiggering the prompt when we've forked off a new debugger.
 
-If the new debugger happened because of a C<system()> that invoked a 
+If the new debugger happened because of a C<system()> that invoked a
 program under the debugger, the arrow between the old pid and the new
 in the prompt has I<two> dashes instead of one.
 
 We take the current list of pids and add this one to the end. If there
-isn't any list yet, we make one up out of the initial pid associated with 
-the terminal and our new pid, sticking an arrow (either one-dashed or 
+isn't any list yet, we make one up out of the initial pid associated with
+the terminal and our new pid, sticking an arrow (either one-dashed or
 two dashed) in between them.
 
 If C<CreateTTY> is off, or C<resetterm> was called with no arguments,
@@ -6350,8 +6519,8 @@ If there are any filehandles there, read from the last one, and return the line
 if we got one. If not, we pop the filehandle off and close it, and try the
 next one up the stack.
 
-If we've emptied the filehandle stack, we check to see if we've got a socket 
-open, and we read that and return it if we do. If we don't, we just call the 
+If we've emptied the filehandle stack, we check to see if we've got a socket
+open, and we read that and return it if we do. If we don't, we just call the
 core C<readline()> and return its value.
 
 =cut
@@ -6361,6 +6530,20 @@ sub readline {
     # Localize to prevent it from being smashed in the program being debugged.
     local $.;
 
+    # If there are stacked filehandles to read from ...
+    # (Handle it before the typeahead, because we may call source/etc. from
+    # the typeahead.)
+    while (@cmdfhs) {
+
+        # Read from the last one in the stack.
+        my $line = CORE::readline( $cmdfhs[-1] );
+
+        # If we got a line ...
+        defined $line
+          ? ( print $OUT ">> $line" and return $line )    # Echo and return
+          : close pop @cmdfhs;                            # Pop and close
+    } ## end while (@cmdfhs)
+
     # Pull a line out of the typeahead if there's stuff there.
     if (@typeahead) {
 
@@ -6386,18 +6569,6 @@ sub readline {
     local $frame = 0;
     local $doret = -2;
 
-    # If there are stacked filehandles to read from ...
-    while (@cmdfhs) {
-
-        # Read from the last one in the stack.
-        my $line = CORE::readline( $cmdfhs[-1] );
-
-        # If we got a line ...
-        defined $line
-          ? ( print $OUT ">> $line" and return $line )    # Echo and return
-          : close pop @cmdfhs;                            # Pop and close
-    } ## end while (@cmdfhs)
-
     # Nothing on the filehandle stack. Socket?
     if ( ref $OUT and UNIVERSAL::isa( $OUT, 'IO::Socket::INET' ) ) {
 
@@ -6405,21 +6576,24 @@ sub readline {
         $OUT->write( join( '', @_ ) );
 
         # Receive anything there is to receive.
-        $stuff;
         my $stuff = '';
         my $buf;
-        do {
+        my $first_time = 1;
+
+        while ($first_time or (length($buf) && ($stuff .= $buf) !~ /\n/))
+        {
+            $first_time = 0;
             $IN->recv( $buf = '', 2048 );   # XXX "what's wrong with sysread?"
                                             # XXX Don't know. You tell me.
-        } while length $buf and ($stuff .= $buf) !~ /\n/;
+        }
 
         # What we got.
-        $stuff;
+        return $stuff;
     } ## end if (ref $OUT and UNIVERSAL::isa...
 
     # No socket. Just read from the terminal.
     else {
-        $term->readline(@_);
+        return $term->readline(@_);
     }
 } ## end sub readline
 
@@ -6511,7 +6685,7 @@ If C<option=value> is entered, we try to extract a quoted string from the
 value (if it is quoted). If it's not, we just use the whole value as-is.
 
 We load any modules required to service this option, and then we set it: if
-it just gets stuck in a variable, we do that; if there's a subroutine to 
+it just gets stuck in a variable, we do that; if there's a subroutine to
 handle setting the option, we call that.
 
 Finally, if we're running in interactive mode, we display the effect of the
@@ -6521,39 +6695,52 @@ during initialization.
 =cut
 
 sub parse_options {
-    local ($_) = @_;
+    my ($s) = @_;
     local $\ = '';
 
+    my $option;
+
     # These options need a value. Don't allow them to be clobbered by accident.
     my %opt_needs_val = map { ( $_ => 1 ) } qw{
       dumpDepth arrayDepth hashDepth LineInfo maxTraceLen ornaments windowSize
       pager quote ReadLine recallCommand RemotePort ShellBang TTY CommandSet
     };
 
-    while (length) {
+    while (length($s)) {
         my $val_defaulted;
 
         # Clean off excess leading whitespace.
-        s/^\s+// && next;
+        $s =~ s/^\s+// && next;
 
         # Options are always all word characters, followed by a non-word
         # separator.
-        s/^(\w+)(\W?)// or print( $OUT "Invalid option '$_'\n" ), last;
+        if ($s !~ s/^(\w+)(\W?)//) {
+            print {$OUT} "Invalid option '$s'\n";
+            last;
+        }
         my ( $opt, $sep ) = ( $1, $2 );
 
         # Make sure that such an option exists.
-        my $matches = grep( /^\Q$opt/ && ( $option = $_ ), @options )
-          || grep( /^\Q$opt/i && ( $option = $_ ), @options );
+        my $matches = ( grep { /^\Q$opt/ && ( $option = $_ ) } @options )
+          || ( grep { /^\Q$opt/i && ( $option = $_ ) } @options );
 
-        print( $OUT "Unknown option '$opt'\n" ), next unless $matches;
-        print( $OUT "Ambiguous option '$opt'\n" ), next if $matches > 1;
+        unless ($matches) {
+            print {$OUT} "Unknown option '$opt'\n";
+            next;
+        }
+        if ($matches > 1) {
+            print {$OUT} "Ambiguous option '$opt'\n";
+            next;
+        }
         my $val;
 
         # '?' as separator means query, but must have whitespace after it.
         if ( "?" eq $sep ) {
-            print( $OUT "Option query '$opt?' followed by non-space '$_'\n" ),
-              last
-              if /^\S/;
+            if ($s =~ /\A\S/) {
+                print {$OUT} "Option query '$opt?' followed by non-space '$s'\n" ;
+
+                last;
+            }
 
             #&dump_option($opt);
         } ## end if ("?" eq $sep)
@@ -6569,14 +6756,14 @@ sub parse_options {
         elsif ( $sep eq "=" ) {
 
             # If quoted, extract a quoted string.
-            if (s/ (["']) ( (?: \\. | (?! \1 ) [^\\] )* ) \1 //x) {
+            if ($s =~ s/ (["']) ( (?: \\. | (?! \1 ) [^\\] )* ) \1 //x) {
                 my $quote = $1;
                 ( $val = $2 ) =~ s/\\([$quote\\])/$1/g;
             }
 
             # Not quoted. Use the whole thing. Warn about 'option='.
             else {
-                s/^(\S*)//;
+                $s =~ s/^(\S*)//;
                 $val = $1;
                 print OUT qq(Option better cleared using $opt=""\n)
                   unless length $val;
@@ -6588,7 +6775,7 @@ sub parse_options {
         else {    #{ to "let some poor schmuck bounce on the % key in B<vi>."
             my ($end) =
               "\\" . substr( ")]>}$sep", index( "([<{", $sep ), 1 );    #}
-            s/^(([^\\$end]|\\[\\$end])*)$end($|\s+)//
+            $s =~ s/^(([^\\$end]|\\[\\$end])*)$end($|\s+)//
               or print( $OUT "Unclosed option value '$opt$sep$_'\n" ), last;
             ( $val = $1 ) =~ s/\\([\\$end])/$1/g;
         } ## end else [ if ("?" eq $sep)
@@ -6596,7 +6783,7 @@ sub parse_options {
         # Exclude non-booleans from getting set to 1 by default.
         if ( $opt_needs_val{$option} && $val_defaulted ) {
             my $cmd = ( $CommandSet eq '580' ) ? 'o' : 'O';
-            print $OUT
+            print {$OUT}
 "Option '$opt' is non-boolean.  Use '$cmd $option=VAL' to set, '$cmd $option?' to query\n";
             next;
         } ## end if ($opt_needs_val{$option...
@@ -6605,35 +6792,37 @@ sub parse_options {
         $option{$option} = $val if defined $val;
 
         # Load any module that this option requires.
-        eval qq{
-                local \$frame = 0; 
-                local \$doret = -2; 
-                require '$optionRequire{$option}';
-                1;
-               } || die $@   # XXX: shouldn't happen
-          if defined $optionRequire{$option}
-          && defined $val;
+        if ( defined($optionRequire{$option}) && defined($val) ) {
+            eval qq{
+            local \$frame = 0;
+            local \$doret = -2;
+            require '$optionRequire{$option}';
+            1;
+            } || die $@   # XXX: shouldn't happen
+        }
 
         # Set it.
         # Stick it in the proper variable if it goes in a variable.
-        ${ $optionVars{$option} } = $val
-          if defined $optionVars{$option}
-          && defined $val;
+        if (defined($optionVars{$option}) && defined($val)) {
+            ${ $optionVars{$option} } = $val;
+        }
 
         # Call the appropriate sub if it gets set via sub.
-        &{ $optionAction{$option} }($val)
-          if defined $optionAction{$option}
-          && defined &{ $optionAction{$option} }
-          && defined $val;
+        if (defined($optionAction{$option})
+          && defined (&{ $optionAction{$option} })
+          && defined ($val))
+        {
+          &{ $optionAction{$option} }($val);
+        }
 
         # Not initialization - echo the value we set it to.
-        dump_option($option) unless $OUT eq \*STDERR;
+        dump_option($option) if ($OUT ne \*STDERR);
     } ## end while (length)
 } ## end sub parse_options
 
 =head1 RESTART SUPPORT
 
-These routines are used to store (and restore) lists of items in environment 
+These routines are used to store (and restore) lists of items in environment
 variables during a restart.
 
 =head2 set_list
@@ -6654,7 +6843,7 @@ sub set_list {
 
     # Grab each item in the list, escape the backslashes, encode the non-ASCII
     # as hex, and then save in the appropriate VAR_0, VAR_1, etc.
-    for $i ( 0 .. $#list ) {
+    for my $i ( 0 .. $#list ) {
         $val = $list[$i];
         $val =~ s/\\/\\\\/g;
         $val =~ s/([\0-\37\177\200-\377])/"\\0x" . unpack('H2',$1)/eg;
@@ -6667,14 +6856,14 @@ sub set_list {
 Reverse the set_list operation: grab VAR_n to see how many we should be getting
 back, and then pull VAR_0, VAR_1. etc. back out.
 
-=cut 
+=cut
 
 sub get_list {
     my $stem = shift;
     my @list;
     my $n = delete $ENV{"${stem}_n"};
     my $val;
-    for $i ( 0 .. $n - 1 ) {
+    for my $i ( 0 .. $n - 1 ) {
         $val = delete $ENV{"${stem}_$i"};
         $val =~ s/\\((\\)|0x(..))/ $2 ? $2 : pack('H2', $3) /ge;
         push @list, $val;
@@ -6687,7 +6876,7 @@ sub get_list {
 =head2 catch()
 
 The C<catch()> subroutine is the essence of fast and low-impact. We simply
-set an already-existing global scalar variable to a constant value. This 
+set an already-existing global scalar variable to a constant value. This
 avoids allocating any memory possibly in the middle of something that will
 get all confused if we do, particularly under I<unsafe signals>.
 
@@ -6703,9 +6892,9 @@ sub catch {
 C<warn> emits a warning, by joining together its arguments and printing
 them, with couple of fillips.
 
-If the composited message I<doesn't> end with a newline, we automatically 
-add C<$!> and a newline to the end of the message. The subroutine expects $OUT 
-to be set to the filehandle to be used to output warnings; it makes no 
+If the composited message I<doesn't> end with a newline, we automatically
+add C<$!> and a newline to the end of the message. The subroutine expects $OUT
+to be set to the filehandle to be used to output warnings; it makes no
 assumptions about what filehandles are available.
 
 =cut
@@ -6722,7 +6911,7 @@ sub warn {
 =head2 C<reset_IN_OUT>
 
 This routine handles restoring the debugger's input and output filehandles
-after we've tried and failed to move them elsewhere.  In addition, it assigns 
+after we've tried and failed to move them elsewhere.  In addition, it assigns
 the debugger's output filehandle to $LINEINFO if it was already open there.
 
 =cut
@@ -6747,9 +6936,7 @@ sub reset_IN_OUT {
     }
 
     # Unbuffer the output filehandle.
-    my $o = select $OUT;
-    $| = 1;
-    select $o;
+    $OUT->autoflush(1);
 
     # Point LINEINFO to the same output filehandle if it was there before.
     $LINEINFO = $OUT if $switch_li;
@@ -6757,7 +6944,7 @@ sub reset_IN_OUT {
 
 =head1 OPTION SUPPORT ROUTINES
 
-The following routines are used to process some of the more complicated 
+The following routines are used to process some of the more complicated
 debugger options.
 
 =head2 C<TTY>
@@ -6832,7 +7019,7 @@ sub noTTY {
 
 =head2 C<ReadLine>
 
-Sets the C<$rl> option variable. If 0, we use C<Term::ReadLine::Stub> 
+Sets the C<$rl> option variable. If 0, we use C<Term::ReadLine::Stub>
 (essentially, no C<readline> processing on this I<terminal>). Otherwise, we
 use C<Term::ReadLine>. Can't be changed after a terminal's in place; we save
 the value in case a restart is done so we can change it then.
@@ -6923,7 +7110,7 @@ sub pager {
 
 =head2 C<shellBang>
 
-Sets the shell escape command, and generates a printable copy to be used 
+Sets the shell escape command, and generates a printable copy to be used
 in the help.
 
 =cut
@@ -6950,7 +7137,7 @@ If the terminal has its own ornaments, fetch them. Otherwise accept whatever
 was passed as the argument. (This means you can't override the terminal's
 ornaments.)
 
-=cut 
+=cut
 
 sub ornaments {
     if ( defined $term ) {
@@ -6996,32 +7183,30 @@ sub recallCommand {
 
 Called with no arguments, returns the file or pipe that line info should go to.
 
-Called with an argument (a file or a pipe), it opens that onto the 
-C<LINEINFO> filehandle, unbuffers the filehandle, and then returns the 
+Called with an argument (a file or a pipe), it opens that onto the
+C<LINEINFO> filehandle, unbuffers the filehandle, and then returns the
 file or pipe again to the caller.
 
 =cut
 
 sub LineInfo {
-    return $lineinfo unless @_;
-    $lineinfo = shift;
+    if (@_) {
+        $lineinfo = shift;
 
-    #  If this is a valid "thing to be opened for output", tack a
-    # '>' onto the front.
-    my $stream = ( $lineinfo =~ /^(\+?\>|\|)/ ) ? $lineinfo : ">$lineinfo";
+        #  If this is a valid "thing to be opened for output", tack a
+        # '>' onto the front.
+        my $stream = ( $lineinfo =~ /^(\+?\>|\|)/ ) ? $lineinfo : ">$lineinfo";
 
-    # If this is a pipe, the stream points to a slave editor.
-    $slave_editor = ( $stream =~ /^\|/ );
+        # If this is a pipe, the stream points to a slave editor.
+        $slave_editor = ( $stream =~ /^\|/ );
 
-    # Open it up and unbuffer it.
-    open( LINEINFO, "$stream" ) || &warn("Cannot open '$stream' for write");
-    $LINEINFO = \*LINEINFO;
-    my $save = select($LINEINFO);
-    $| = 1;
-    select($save);
+        # Open it up and unbuffer it.
+        open( LINEINFO, $stream ) || &warn("Cannot open '$stream' for write");
+        $LINEINFO = \*LINEINFO;
+        $LINEINFO->autoflush(1);
+    }
 
-    # Hand the file or pipe back again.
-    $lineinfo;
+    return $lineinfo;
 } ## end sub LineInfo
 
 =head1 COMMAND SUPPORT ROUTINES
@@ -7053,8 +7238,9 @@ sub list_modules {    # versions
 
         # If the package has a $VERSION package global (as all good packages
         # should!) decode it and save as partial message.
-        if ( defined ${ $_ . '::VERSION' } ) {
-            $version{$file} = "${ $_ . '::VERSION' } from ";
+        my $pkg_version = do { no strict 'refs'; ${ $_ . '::VERSION' } };
+        if ( defined $pkg_version ) {
+            $version{$file} = "$pkg_version from ";
         }
 
         # Finish up the message with the file the package came from.
@@ -7082,12 +7268,15 @@ newline. The descriptive text can also be marked up in the same way. If you
 need to continue the descriptive text to another line, start that line with
 just tabs and then enter the marked-up text.
 
-If you are modifying the help text, I<be careful>. The help-string parser is 
-not very sophisticated, and if you don't follow these rules it will mangle the 
+If you are modifying the help text, I<be careful>. The help-string parser is
+not very sophisticated, and if you don't follow these rules it will mangle the
 help beyond hope until you fix the string.
 
 =cut
 
+use vars qw($pre580_help);
+use vars qw($pre580_summary);
+
 sub sethelp {
 
     # XXX: make sure there are tabs between the command and explanation,
@@ -7095,8 +7284,8 @@ sub sethelp {
     #      eeevil ornaments enabled.  This is an insane mess.
 
     $help = "
-Help is currently only available for the new 5.8 command set. 
-No help is available for the old command set. 
+Help is currently only available for the new 5.8 command set.
+No help is available for the old command set.
 We assume you know what you're doing if you switch to it.
 
 B<T>        Stack trace.
@@ -7137,7 +7326,7 @@ B<b> I<subname> [I<condition>]
 B<b> I<\$var>        Set breakpoint at first line of subroutine referenced by I<\$var>.
 B<b> B<load> I<filename> Set breakpoint on 'require'ing the given file.
 B<b> B<postpone> I<subname> [I<condition>]
-        Set breakpoint at first line of subroutine after 
+        Set breakpoint at first line of subroutine after
         it is compiled.
 B<b> B<compile> I<subname>
         Stop after the subroutine is compiled.
@@ -7208,12 +7397,12 @@ I<command>        Execute as a perl statement in current package.
 B<R>        Pure-man-restart of debugger, some of debugger state
         and command-line options may be lost.
         Currently the following settings are preserved:
-        history, breakpoints and actions, debugger B<O>ptions 
+        history, breakpoints and actions, debugger B<O>ptions
         and the following command-line options: I<-w>, I<-I>, I<-e>.
 
 B<o> [I<opt>] ...    Set boolean option to true
 B<o> [I<opt>B<?>]    Query options
-B<o> [I<opt>B<=>I<val>] [I<opt>=B<\">I<val>B<\">] ... 
+B<o> [I<opt>B<=>I<val>] [I<opt>=B<\">I<val>B<\">] ...
         Set options.  Use quotes if spaces in value.
     I<recallCommand>, I<ShellBang>    chars used to recall command or spawn shell;
     I<pager>            program for output of \"|cmd\";
@@ -7249,7 +7438,7 @@ B<q> or B<^D>        Quit. Set B<\$DB::finished = 0> to debug global destruction
 B<h>        Summary of debugger commands.
 B<h> [I<db_command>]    Get help [on a specific debugger command], enter B<|h> to page.
 B<h h>        Long help for debugger commands
-B<$doccmd> I<manpage>    Runs the external doc viewer B<$doccmd> command on the 
+B<$doccmd> I<manpage>    Runs the external doc viewer B<$doccmd> command on the
         named Perl I<manpage>, or on B<$doccmd> itself if omitted.
         Set B<\$DB::doccmd> to change viewer.
 
@@ -7328,7 +7517,7 @@ B<b> I<subname> [I<condition>]
 B<b> I<\$var>        Set breakpoint at first line of subroutine referenced by I<\$var>.
 B<b> B<load> I<filename> Set breakpoint on 'require'ing the given file.
 B<b> B<postpone> I<subname> [I<condition>]
-        Set breakpoint at first line of subroutine after 
+        Set breakpoint at first line of subroutine after
         it is compiled.
 B<b> B<compile> I<subname>
         Stop after the subroutine is compiled.
@@ -7384,12 +7573,12 @@ B<v>        Show versions of loaded modules.
 B<R>        Pure-man-restart of debugger, some of debugger state
         and command-line options may be lost.
         Currently the following settings are preserved:
-        history, breakpoints and actions, debugger B<O>ptions 
+        history, breakpoints and actions, debugger B<O>ptions
         and the following command-line options: I<-w>, I<-I>, I<-e>.
 
 B<O> [I<opt>] ...    Set boolean option to true
 B<O> [I<opt>B<?>]    Query options
-B<O> [I<opt>B<=>I<val>] [I<opt>=B<\">I<val>B<\">] ... 
+B<O> [I<opt>B<=>I<val>] [I<opt>=B<\">I<val>B<\">] ...
         Set options.  Use quotes if spaces in value.
     I<recallCommand>, I<ShellBang>    chars used to recall command or spawn shell;
     I<pager>            program for output of \"|cmd\";
@@ -7424,7 +7613,7 @@ B<O> [I<opt>B<=>I<val>] [I<opt>=B<\">I<val>B<\">] ...
 B<q> or B<^D>        Quit. Set B<\$DB::finished = 0> to debug global destruction.
 B<h> [I<db_command>]    Get help [on a specific debugger command], enter B<|h> to page.
 B<h h>        Summary of debugger commands.
-B<$doccmd> I<manpage>    Runs the external doc viewer B<$doccmd> command on the 
+B<$doccmd> I<manpage>    Runs the external doc viewer B<$doccmd> command on the
         named Perl I<manpage>, or on B<$doccmd> itself if omitted.
         Set B<\$DB::doccmd> to change viewer.
 
@@ -7468,13 +7657,13 @@ END_SUM
 
 Most of what C<print_help> does is just text formatting. It finds the
 C<B> and C<I> ornaments, cleans them off, and substitutes the proper
-terminal control characters to simulate them (courtesy of 
+terminal control characters to simulate them (courtesy of
 C<Term::ReadLine::TermCap>).
 
 =cut
 
 sub print_help {
-    local $_ = shift;
+    my $help_str = (@_);
 
     # Restore proper alignment destroyed by eeevil I<> and B<>
     # ornaments: A pox on both their houses!
@@ -7482,18 +7671,18 @@ sub print_help {
     # A help command will have everything up to and including
     # the first tab sequence padded into a field 16 (or if indented 20)
     # wide.  If it's wider than that, an extra space will be added.
-    s{
+    $help_str =~ s{
         ^                       # only matters at start of line
           ( \040{4} | \t )*     # some subcommands are indented
           ( < ?                 # so <CR> works
             [BI] < [^\t\n] + )  # find an eeevil ornament
           ( \t+ )               # original separation, discarded
-          ( .* )                # this will now start (no earlier) than 
+          ( .* )                # this will now start (no earlier) than
                                 # column 16
     } {
         my($leadwhite, $command, $midwhite, $text) = ($1, $2, $3, $4);
         my $clean = $command;
-        $clean =~ s/[BI]<([^>]*)>/$1/g;  
+        $clean =~ s/[BI]<([^>]*)>/$1/g;
 
         # replace with this whole string:
         ($leadwhite ? " " x 4 : "")
@@ -7503,27 +7692,29 @@ sub print_help {
 
     }mgex;
 
-    s{                          # handle bold ornaments
+    $help_str =~ s{                          # handle bold ornaments
        B < ( [^>] + | > ) >
     } {
-          $Term::ReadLine::TermCap::rl_term_set[2] 
+          $Term::ReadLine::TermCap::rl_term_set[2]
         . $1
         . $Term::ReadLine::TermCap::rl_term_set[3]
     }gex;
 
-    s{                         # handle italic ornaments
+    $help_str =~ s{                         # handle italic ornaments
        I < ( [^>] + | > ) >
     } {
-          $Term::ReadLine::TermCap::rl_term_set[0] 
+          $Term::ReadLine::TermCap::rl_term_set[0]
         . $1
         . $Term::ReadLine::TermCap::rl_term_set[1]
     }gex;
 
     local $\ = '';
-    print $OUT $_;
+    print {$OUT} $help_str;
+
+    return;
 } ## end sub print_help
 
-=head2 C<fix_less> 
+=head2 C<fix_less>
 
 This routine does a lot of gyrations to be sure that the pager is C<less>.
 It checks for C<less> masquerading as C<more> and records the result in
@@ -7531,29 +7722,42 @@ C<$fixed_less> so we don't have to go through doing the stats again.
 
 =cut
 
-sub fix_less {
-
-    # We already know if this is set.
-    return if $fixed_less;
-
-    # Pager is less for sure.
-    my $is_less = $pager =~ /\bless\b/;
-    if ( $pager =~ /\bmore\b/ ) {
+use vars qw($fixed_less);
 
+sub _calc_is_less {
+    if ($pager =~ /\bless\b/)
+    {
+        return 1;
+    }
+    elsif ($pager =~ /\bmore\b/)
+    {
         # Nope, set to more. See what's out there.
         my @st_more = stat('/usr/bin/more');
         my @st_less = stat('/usr/bin/less');
 
         # is it really less, pretending to be more?
-             $is_less = @st_more
-          && @st_less
-          && $st_more[0] == $st_less[0]
-          && $st_more[1] == $st_less[1];
-    } ## end if ($pager =~ /\bmore\b/)
+        return (
+            @st_more
+            && @st_less
+            && $st_more[0] == $st_less[0]
+            && $st_more[1] == $st_less[1]
+        );
+    }
+    else {
+        return;
+    }
+}
+
+sub fix_less {
+
+    # We already know if this is set.
+    return if $fixed_less;
 
     # changes environment!
     # 'r' added so we don't do (slow) stats again.
-    $fixed_less = 1 if $is_less;
+    $fixed_less = 1 if _calc_is_less();
+
+    return;
 } ## end sub fix_less
 
 =head1 DIE AND WARN MANAGEMENT
@@ -7659,14 +7863,14 @@ sub dbwarn {
 =head2 C<dbdie>
 
 The debugger's own C<$SIG{__DIE__}> handler. Handles providing a stack trace
-by loading C<Carp> and calling C<Carp::longmess()> to get it. We turn off 
-single stepping and tracing during the call to C<Carp::longmess> to avoid 
+by loading C<Carp> and calling C<Carp::longmess()> to get it. We turn off
+single stepping and tracing during the call to C<Carp::longmess> to avoid
 debugging it - we just want to use it.
 
 If C<dieLevel> is zero, we let the program being debugged handle the
 exceptions. If it's 1, you get backtraces for any exception. If it's 2,
 the debugger takes over all exception handling, printing a backtrace and
-displaying the exception via its C<dbwarn()> routine. 
+displaying the exception via its C<dbwarn()> routine.
 
 =cut
 
@@ -7724,7 +7928,7 @@ being debugged in place.
 
 sub warnLevel {
     if (@_) {
-        $prevwarn = $SIG{__WARN__} unless $warnLevel;
+        my $prevwarn = $SIG{__WARN__} unless $warnLevel;
         $warnLevel = shift;
         if ($warnLevel) {
             $SIG{__WARN__} = \&DB::dbwarn;
@@ -7740,7 +7944,7 @@ sub warnLevel {
 
 =head2 C<dielevel>
 
-Similar to C<warnLevel>. Non-zero values for C<dieLevel> result in the 
+Similar to C<warnLevel>. Non-zero values for C<dieLevel> result in the
 C<DB::dbdie()> function overriding any other C<die()> handler. Setting it to
 zero lets you use your own C<die()> handler.
 
@@ -7749,7 +7953,7 @@ zero lets you use your own C<die()> handler.
 sub dieLevel {
     local $\ = '';
     if (@_) {
-        $prevdie = $SIG{__DIE__} unless $dieLevel;
+        my $prevdie = $SIG{__DIE__} unless $dieLevel;
         $dieLevel = shift;
         if ($dieLevel) {
 
@@ -7785,15 +7989,15 @@ sub dieLevel {
 =head2 C<signalLevel>
 
 Number three in a series: set C<signalLevel> to zero to keep your own
-signal handler for C<SIGSEGV> and/or C<SIGBUS>. Otherwise, the debugger 
+signal handler for C<SIGSEGV> and/or C<SIGBUS>. Otherwise, the debugger
 takes over and handles them with C<DB::diesignal()>.
 
 =cut
 
 sub signalLevel {
     if (@_) {
-        $prevsegv = $SIG{SEGV} unless $signalLevel;
-        $prevbus  = $SIG{BUS}  unless $signalLevel;
+        my $prevsegv = $SIG{SEGV} unless $signalLevel;
+        my $prevbus  = $SIG{BUS}  unless $signalLevel;
         $signalLevel = shift;
         if ($signalLevel) {
             $SIG{SEGV} = \&DB::diesignal;
@@ -7839,6 +8043,8 @@ Returns C<< I<package>::I<glob name> >> if the code ref is found in a glob.
 
 =cut
 
+use vars qw($skipCvGV);
+
 sub CvGV_name_or_bust {
     my $in = shift;
     return if $skipCvGV;    # Backdoor to avoid problems if XS broken...
@@ -7851,7 +8057,7 @@ sub CvGV_name_or_bust {
 
 =head2 C<find_sub>
 
-A utility routine used in various places; finds the file where a subroutine 
+A utility routine used in various places; finds the file where a subroutine
 was defined, and returns that filename and a line-number range.
 
 Tries to use C<@sub> first; if it can't find it there, it tries building a
@@ -7861,33 +8067,47 @@ this way, it brute-force searches C<%sub>, checking for identical references.
 
 =cut
 
+sub _find_sub_helper {
+    my $subr = shift;
+
+    return unless defined &$subr;
+    my $name = CvGV_name_or_bust($subr);
+    my $data;
+    $data = $sub{$name} if defined $name;
+    return $data if defined $data;
+
+    # Old stupid way...
+    $subr = \&$subr;    # Hard reference
+    my $s;
+    for ( keys %sub ) {
+        $s = $_, last if $subr eq \&$_;
+    }
+    if ($s)
+    {
+        return $sub{$s};
+    }
+    else
+    {
+        return;
+    }
+
+}
+
 sub find_sub {
     my $subr = shift;
-    $sub{$subr} or do {
-        return unless defined &$subr;
-        my $name = CvGV_name_or_bust($subr);
-        my $data;
-        $data = $sub{$name} if defined $name;
-        return $data if defined $data;
-
-        # Old stupid way...
-        $subr = \&$subr;    # Hard reference
-        my $s;
-        for ( keys %sub ) {
-            $s = $_, last if $subr eq \&$_;
-        }
-        $sub{$s} if $s;
-      } ## end do
+    return ( $sub{$subr} || _find_sub_helper($subr) );
 } ## end sub find_sub
 
 =head2 C<methods>
 
 A subroutine that uses the utility function C<methods_via> to find all the
-methods in the class corresponding to the current reference and in 
+methods in the class corresponding to the current reference and in
 C<UNIVERSAL>.
 
 =cut
 
+use vars qw(%seen);
+
 sub methods {
 
     # Figure out the class - either this is the class or it's a reference
@@ -7926,7 +8146,8 @@ sub methods_via {
     my @to_print;
 
     # Extract from all the symbols in this class.
-    while (my ($name, $glob) = each %{"${class}::"}) {
+    my $class_ref = do { no strict "refs"; \%{$class . '::'} };
+    while (my ($name, $glob) = each %$class_ref) {
        # references directly in the symbol table are Proxy Constant
        # Subroutines, and are by their very nature defined
        # Otherwise, check if the thing is a typeglob, and if it is, it decays
@@ -7951,7 +8172,8 @@ sub methods_via {
 
     # $crawl_upward true: keep going up the tree.
     # Find all the classes this one is a subclass of.
-    for $name ( @{"${class}::ISA"} ) {
+    my $class_ISA_ref = do { no strict "refs"; \@{"${class}::ISA"} };
+    for my $name ( @$class_ISA_ref ) {
 
         # Set up the new prefix.
         $prepend = $prefix ? $prefix . " -> $name" : $name;
@@ -7981,48 +8203,8 @@ program's STDIN and STDOUT.
 
 =cut
 
-sub runman {
-    my $page = shift;
-    unless ($page) {
-        &system("$doccmd $doccmd");
-        return;
-    }
-
-    # this way user can override, like with $doccmd="man -Mwhatever"
-    # or even just "man " to disable the path check.
-    unless ( $doccmd eq 'man' ) {
-        &system("$doccmd $page");
-        return;
-    }
-
-    $page = 'perl' if lc($page) eq 'help';
-
-    require Config;
-    my $man1dir = $Config::Config{'man1dir'};
-    my $man3dir = $Config::Config{'man3dir'};
-    for ( $man1dir, $man3dir ) { s#/[^/]*\z## if /\S/ }
-    my $manpath = '';
-    $manpath .= "$man1dir:" if $man1dir =~ /\S/;
-    $manpath .= "$man3dir:" if $man3dir =~ /\S/ && $man1dir ne $man3dir;
-    chop $manpath if $manpath;
-
-    # harmless if missing, I figure
-    my $oldpath = $ENV{MANPATH};
-    $ENV{MANPATH} = $manpath if $manpath;
-    my $nopathopt = $^O =~ /dunno what goes here/;
-    if (
-        CORE::system(
-            $doccmd,
-
-            # I just *know* there are men without -M
-            ( ( $manpath && !$nopathopt ) ? ( "-M", $manpath ) : () ),
-            split ' ', $page
-        )
-      )
-    {
-        unless ( $page =~ /^perl\w/ ) {
-# do it this way because its easier to slurp in to keep up to date - clunky though.
-my @pods = qw(
+my %_is_in_pods = (map { $_ => 1 }
+    qw(
     5004delta
     5005delta
     561delta
@@ -8107,7 +8289,6 @@ my @pods = qw(
     modlib
     mod
     modstyle
-    mpeix
     netware
     newmod
     number
@@ -8149,20 +8330,61 @@ my @pods = qw(
     util
     uts
     var
-    vmesa
     vms
     vos
     win32
     xs
     xstut
+    )
 );
-            if (grep { $page eq $_ } @pods) {
-                $page =~ s/^/perl/;
+
+sub runman {
+    my $page = shift;
+    unless ($page) {
+        &system("$doccmd $doccmd");
+        return;
+    }
+
+    # this way user can override, like with $doccmd="man -Mwhatever"
+    # or even just "man " to disable the path check.
+    unless ( $doccmd eq 'man' ) {
+        &system("$doccmd $page");
+        return;
+    }
+
+    $page = 'perl' if lc($page) eq 'help';
+
+    require Config;
+    my $man1dir = $Config::Config{'man1dir'};
+    my $man3dir = $Config::Config{'man3dir'};
+    for ( $man1dir, $man3dir ) { s#/[^/]*\z## if /\S/ }
+    my $manpath = '';
+    $manpath .= "$man1dir:" if $man1dir =~ /\S/;
+    $manpath .= "$man3dir:" if $man3dir =~ /\S/ && $man1dir ne $man3dir;
+    chop $manpath if $manpath;
+
+    # harmless if missing, I figure
+    my $oldpath = $ENV{MANPATH};
+    $ENV{MANPATH} = $manpath if $manpath;
+    my $nopathopt = $^O =~ /dunno what goes here/;
+    if (
+        CORE::system(
+            $doccmd,
+
+            # I just *know* there are men without -M
+            ( ( $manpath && !$nopathopt ) ? ( "-M", $manpath ) : () ),
+            split ' ', $page
+        )
+      )
+    {
+        unless ( $page =~ /^perl\w/ ) {
+# do it this way because its easier to slurp in to keep up to date - clunky though.
+            if (exists($_is_in_pods{$page})) {
                 CORE::system( $doccmd,
                     ( ( $manpath && !$nopathopt ) ? ( "-M", $manpath ) : () ),
-                    $page );
-            } ## end if (grep { $page eq $_...
-        } ## end unless ($page =~ /^perl\w/)
+                    "perl$page" );
+            }
+        }
     } ## end if (CORE::system($doccmd...
     if ( defined $oldpath ) {
         $ENV{MANPATH} = $manpath;
@@ -8184,7 +8406,7 @@ This block sets things up so that (basically) the world is sane
 before the debugger starts executing. We set up various variables that the
 debugger has to have set up before the Perl core starts running:
 
-=over 4 
+=over 4
 
 =item *
 
@@ -8236,6 +8458,8 @@ That we want no return values and no subroutine entry/exit trace.
 
 # The following BEGIN is very handy if debugger goes havoc, debugging debugger?
 
+use vars qw($db_stop);
+
 BEGIN {    # This does not compile, alas. (XXX eh?)
     $IN  = \*STDIN;     # For bugs before DB::OUT has been opened
     $OUT = \*STDERR;    # For errors before DB::OUT has been opened
@@ -8287,7 +8511,7 @@ BEGIN {    # This does not compile, alas. (XXX eh?)
     # "Triggers bug (?) in perl if we postpone this until runtime."
     # XXX No details on this yet, or whether we should fix the bug instead
     # of work around it. Stay tuned.
-    @postponed = @stack = (0);
+    @stack = (0);
 
     # Used to track the current stack depth using the auto-stacked-variable
     # trick.
@@ -8307,14 +8531,14 @@ BEGIN { $^W = $ini_warn; }    # Switch warnings back
 
 =head2 db_complete
 
-C<readline> support - adds command completion to basic C<readline>. 
+C<readline> support - adds command completion to basic C<readline>.
 
 Returns a list of possible completions to C<readline> when invoked. C<readline>
-will print the longest common substring following the text already entered. 
+will print the longest common substring following the text already entered.
 
 If there is only a single possible completion, C<readline> will use it in full.
 
-This code uses C<map> and C<grep> heavily to create lists of possible 
+This code uses C<map> and C<grep> heavily to create lists of possible
 completion. Think LISP in this section.
 
 =cut
@@ -8331,9 +8555,9 @@ sub db_complete {
     # The search pattern is current package, ::, extract the next qualifier
     # Prefix and pack are set to undef.
     my ( $itext, $search, $prefix, $pack ) =
-      ( $text, "^\Q${'package'}::\E([^:]+)\$" );
+      ( $text, "^\Q${package}::\E([^:]+)\$" );
 
-=head3 C<b postpone|compile> 
+=head3 C<b postpone|compile>
 
 =over 4
 
@@ -8359,7 +8583,7 @@ Return this as the list of possible completions
 
 =back
 
-=cut 
+=cut
 
     return sort grep /^\Q$text/, ( keys %sub ),
       qw(postpone load compile),    # subroutines
@@ -8396,14 +8620,15 @@ get all possible matching packages. Return this sorted list.
 
 Take a partially-qualified package and find all subpackages for it
 by getting all the subpackages for the package so far, matching all
-the subpackages against the text, and discarding all of them which 
+the subpackages against the text, and discarding all of them which
 start with 'main::'. Return this list.
 
 =cut
 
     return sort map { ( $_, db_complete( $_ . "::", "V ", 2 ) ) }
       grep !/^main::/, grep /^\Q$text/,
-      map { /^(.*)::$/ ? ( $prefix . "::$1" ) : () } keys %{ $prefix . '::' }
+      map { /^(.*)::$/ ? ( $prefix . "::$1" ) : () }
+      do { no strict 'refs'; keys %{ $prefix . '::' } }
       if ( substr $line, 0, $start ) =~ /^\|*[Vm]\s+$/
       and $text =~ /^(.*[^:])::?(\w*)$/
       and $prefix = $1;
@@ -8434,9 +8659,9 @@ Possibilities are:
 
 =pod
 
-Under the debugger, source files are represented as C<_E<lt>/fullpath/to/file> 
-(C<eval>s are C<_E<lt>(eval NNN)>) keys in C<%main::>. We pull all of these 
-out of C<%main::>, add the initial source file, and extract the ones that 
+Under the debugger, source files are represented as C<_E<lt>/fullpath/to/file>
+(C<eval>s are C<_E<lt>(eval NNN)>) keys in C<%main::>. We pull all of these
+out of C<%main::>, add the initial source file, and extract the ones that
 match the completion text so far.
 
 =cut
@@ -8474,7 +8699,7 @@ Much like the above, except we have to do a little more cleanup:
 
 =pod
 
-=over 4 
+=over 4
 
 =item *
 
@@ -8503,8 +8728,11 @@ Look through all the symbols in the package. C<grep> out all the possible hashes
 
 =cut
 
-        my @out = map "$prefix$_", grep /^\Q$text/, grep /^_?[a-zA-Z]/,
-          keys %$pack;
+        my @out = do {
+            no strict 'refs';
+            map "$prefix$_", grep /^\Q$text/, grep /^_?[a-zA-Z]/,
+            keys %$pack;
+        };
 
 =pod
 
@@ -8609,10 +8837,10 @@ If there's only one hit, it's a package qualifier, and it's not equal to the ini
         return sort @out;
     } ## end if ($text =~ /^[\$@%]/)
 
-=head3 Options 
+=head3 Options
 
 We use C<option_val()> to look up the current value of the option. If there's
-only a single value, we complete the command in such a way that it is a 
+only a single value, we complete the command in such a way that it is a
 complete command for setting the option in question. If there are multiple
 possible values, we generate a command consisting of the option plus a trailing
 question mark, which, if executed, will list the current value of the option.
@@ -8642,7 +8870,7 @@ question mark, which, if executed, will list the current value of the option.
             # We'll want to quote the string (because of the embedded
             # whtespace), but we want to make sure we don't end up with
             # mismatched quote characters. We try several possibilities.
-            foreach $l ( split //, qq/\"\'\#\|/ ) {
+            foreach my $l ( split //, qq/\"\'\#\|/ ) {
 
                 # If we didn't find this quote character in the value,
                 # quote it using this quote character.
@@ -8799,7 +9027,7 @@ appropriate arguments to rerun the current session.
 =cut
 
 sub rerun {
-    my $i = shift; 
+    my $i = shift;
     my @args;
     pop(@truehist);                      # strim
     unless (defined $truehist[$i]) {
@@ -8853,8 +9081,9 @@ sub restart {
     # the 'require perl5db.pl;' line), and add them back on
     # to the command line to be executed.
     if ( $0 eq '-e' ) {
-        for ( 1 .. $#{'::_<-e'} ) {  # The first line is PERL5DB
-            chomp( $cl = ${'::_<-e'}[$_] );
+        my $lines = *{$main::{'_<-e'}}{ARRAY};
+        for ( 1 .. $#$lines ) {  # The first line is PERL5DB
+            chomp( $cl = $lines->[$_] );
             push @script, '-e', $cl;
         }
     } ## end if ($0 eq '-e')
@@ -8894,7 +9123,7 @@ just popped into environment variables directly.
     # Save the break-on-loads.
     set_list( "PERLDB_ON_LOAD", %break_on_load );
 
-=pod 
+=pod
 
 The most complex part of this is the saving of all of the breakpoints. They
 can live in an awful lot of places, and we have to go through all of them,
@@ -8934,7 +9163,7 @@ variable via C<DB::set_list>.
 
         # Serialize the extra data %breakpoints_data hash.
         # That's a bug fix.
-        set_list( "PERLDB_FILE_ENABLED_$_", 
+        set_list( "PERLDB_FILE_ENABLED_$_",
             map { _is_breakpoint_enabled($file, $_) ? 1 : 0 }
             sort { $a <=> $b } keys(%dbline)
         )
@@ -9003,7 +9232,7 @@ variable via C<DB::set_list>.
     # Set this back to the initial pid.
     $ENV{PERLDB_PIDS} = $ini_pids if defined $ini_pids;
 
-=pod 
+=pod
 
 After all the debugger status has been saved, we take the command we built up
 and then return it, so we can C<exec()> it. The debugger will spot the
@@ -9015,7 +9244,7 @@ from the environment.
     # And run Perl again. Add the "-d" flag, all the
     # flags we built up, the script (whether a one-liner
     # or a file), add on the -emacs flag for a slave editor,
-    # and then the old arguments. 
+    # and then the old arguments.
 
     return ($^X, '-d', @flags, @script, ($slave_editor ? '-emacs' : ()), @ARGS);
 
@@ -9025,9 +9254,9 @@ from the environment.
 
 =head1 END PROCESSING - THE C<END> BLOCK
 
-Come here at the very end of processing. We want to go into a 
-loop where we allow the user to enter commands and interact with the 
-debugger, but we don't want anything else to execute. 
+Come here at the very end of processing. We want to go into a
+loop where we allow the user to enter commands and interact with the
+debugger, but we don't want anything else to execute.
 
 First we set the C<$finished> variable, so that some commands that
 shouldn't be run after the end of program quit working.
@@ -9040,7 +9269,7 @@ We then call C<DB::fake::at_exit()>, which returns the C<Use 'q' to quit ...>
 message and returns control to the debugger. Repeat.
 
 When the user finally enters a C<q> command, C<$fall_off_end> is set to
-1 and the C<END> block simply exits with C<$single> set to 0 (don't 
+1 and the C<END> block simply exits with C<$single> set to 0 (don't
 break, run to completion.).
 
 =cut
@@ -9060,12 +9289,12 @@ END {
 
 =head1 PRE-5.8 COMMANDS
 
-Some of the commands changed function quite a bit in the 5.8 command 
+Some of the commands changed function quite a bit in the 5.8 command
 realignment, so much so that the old code had to be replaced completely.
 Because we wanted to retain the option of being able to go back to the
 former command set, we moved the old code off to this section.
 
-There's an awful lot of duplicated code here. We've duplicated the 
+There's an awful lot of duplicated code here. We've duplicated the
 comments to keep things clear.
 
 =head2 Null command
@@ -9094,8 +9323,8 @@ sub cmd_pre580_a {
     if ( $cmd =~ /^(\d*)\s*(.*)/ ) {
 
         # If the line isn't there, use the current line.
-        $i = $1 || $line;
-        $j = $2;
+        my $i = $1 || $line;
+        my $j = $2;
 
         # If there is an action ...
         if ( length $j ) {
@@ -9130,7 +9359,7 @@ sub cmd_pre580_a {
     } ## end if ($cmd =~ /^(\d*)\s*(.*)/)
 } ## end sub cmd_pre580_a
 
-=head2 Old C<b> command 
+=head2 Old C<b> command
 
 Add breakpoints.
 
@@ -9164,7 +9393,7 @@ sub cmd_pre580_b {
         $subname =~ s/\'/::/g;
 
         # Qualify it into the current package unless it's already qualified.
-        $subname = "${'package'}::" . $subname
+        $subname = "${package}::" . $subname
           unless $subname =~ /::/;
 
         # Add main if it starts with ::.
@@ -9208,11 +9437,11 @@ sub cmd_pre580_D {
             # Switch to the desired file temporarily.
             local *dbline = $main::{ '_<' . $file };
 
-            my $max = $#dbline;
+            $max = $#dbline;
             my $was;
 
             # For all lines in this file ...
-            for ( $i = 1 ; $i <= $max ; $i++ ) {
+            for my $i (1 .. $max) {
 
                 # If there's a breakpoint or action on this line ...
                 if ( defined $dbline{$i} ) {
@@ -9225,7 +9454,7 @@ sub cmd_pre580_D {
                         delete $dbline{$i};
                     }
                 } ## end if (defined $dbline{$i...
-            } ## end for ($i = 1 ; $i <= $max...
+            } ## end for my $i (1 .. $max)
 
             # If, after we turn off the "there were breakpoints in this file"
             # bit, the entry in %had_breakpoints for this file is zero,
@@ -9245,7 +9474,7 @@ sub cmd_pre580_D {
 
 =head2 Old C<h> command
 
-Print help. Defaults to printing the long-form help; the 5.8 version 
+Print help. Defaults to printing the long-form help; the 5.8 version
 prints the summary by default.
 
 =cut
@@ -9345,9 +9574,9 @@ sub cmd_pre580_W {
 
 =head1 PRE-AND-POST-PROMPT COMMANDS AND ACTIONS
 
-The debugger used to have a bunch of nearly-identical code to handle 
+The debugger used to have a bunch of nearly-identical code to handle
 the pre-and-post-prompt action commands. C<cmd_pre590_prepost> and
-C<cmd_prepost> unify all this into one set of code to handle the 
+C<cmd_prepost> unify all this into one set of code to handle the
 appropriate actions.
 
 =head2 C<cmd_pre590_prepost>