The thing is that within "perl -d", each line you type interactively is effectively in it's own block. Try the following:

DB<1> my $x = 1 DB<2> p $x DB<3> $x = 1 DB<4> p $x 1
Notice how the first initialization of $x did not persist, since that $x was a lexical, and hence confined to the scope of that line. The second initialization of $x did persist, however, because this $x is in fact $main::x:
DB<5> p $main::x 1

Update: One other consequence of the fact that every line you type lives in its own block is that global variables that are implicitly localized to the enclosing scope (i.e. regexp-matching variables like $&, $', $`, $1, $2, $3...) will not survive from one line you type to the next. For example

DB<1> 'a' =~ /(.)/ DB<2> print $1 DB<3> 'a' =~ /(.)/ && print $1 a DB<4>
Therefore, if you want to be able to use one of these variables over several lines, assign it to a package global:
DB<5> 'a' =~ /(.)/ && $g = $1 DB<6> print $g a DB<7>

Update: Added some emphasis.

the lowliest monk


In reply to Re: Strange behavior of "my" in "perl -d" and "perl -de" by tlm
in thread Strange behavior of "my" in "perl -d" and "perl -de" by johnnywang

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.