how to restore globals $1, $2, $3 while debugging?

Viewed 70

When I debug code with regular expressions:

m/(.)(.)(.)(.)(.)/;
my $x =  $1;
$DB::single = 1;
my $y =  $2 + $3;

and put break point at some line. I could run third party code. And if that code uses call to regex then $2 and $3 will be broken.

Is there a way to restore $2, and $3 to theirs initial values by debugger when I continue script? ( c debugger command)

2 Answers

It happens automatically.

$ perl -e'
   "abc" =~ /(.)(.)(.)/;
   CORE::say "[$1$2$3]";
   {
      "def" =~ /(.)(.)(.)/;
      CORE::say "{$1$2$3}";
   }
   CORE::say "[$1$2$3]";
'
[abc]
{def}
[abc]

The regex capture vars are implicitly restored when the scope in which they are changed is exited. When you execute code from within the debugger, the regex capture vars are restored before even returning to the debugger.

$ perl -d -e'
   "abc" =~ /(.)(.)(.)/;
   CORE::say "[$1$2$3]";
   CORE::say "[$1$2$3]";
'
[snip]
main::(-e:2):      "abc" =~ /(.)(.)(.)/;
  DB<1> s
main::(-e:3):      CORE::say "[$1$2$3]";
  DB<1> s
[abc]
main::(-e:4):      CORE::say "[$1$2$3]";
  DB<1> p "{$1$2$3}"
{abc}                                              <-- Values from the program
  DB<2> x "def" =~ /(.)(.)(.)/; say "<$1$2$3>";
<def>                                              <-- Changed in called code
0  1
  DB<3> p "{$1$2$3}"
{abc}                                              <-- Already restored
  DB<4> r
[abc]                                              <-- Code has nothing to worry about
Debugged program terminated. [snip]
  DB<4> q

You do have to be careful about changing other variables, such as $!. If the code being debugged cares about the value of $! (for example) and you want to run code that clobbers $!, you'll need to back it up and restore it.

x local $!; clobbering_time();

At this time, the debugger protects $@, $!, $^E, $,, $/, $\ and $^W from being clobbered by the debugger itself, but not by code executed via x.

Can you stash the value in a variable?

m/(.)(.)(.)(.)(.)/;
my ($x, $two, $three) = ($1, $2, $3);
$DB::single = 1;
my $y =  $two + $three;
Related