Hi All, I'm confused about a namespace issue when using Safe. According to the documentation, code executed within a Safe compartment believes that it resides in package main, when in fact it is in a special namespace of $Safe::Root0 (or another name of your choosing). Now, using B::Deparse::coderef2text will return a bare block where the first statement is a package statement reflecting the package in which the code was originally compiled. Something like:

{ package Foo; print "Hello World\n"; }

When running this B::Deparse'd code through Safe::reval, I'd expect the code then to execute within Safe::Root0::Foo. However, as the below example shows, the code thinks it is in package main, as the documentation of Safe says code ought to. Does this mean that package statements in Safe::reval'd strings are wholly ignored, thereby making it pointless to remove them, or is the code actually in Safe::Root0::Foo but believes it's in main?

Package Foo; sub new { my $class = shift; my $this = bless {}, $class; $this->_init(); return $this; } sub _init { my $cpt = new Safe(); my $s = sub {eval q/print "PACKAGE is ",__PACKAGE__,"\n"/; }; # explicitly permit use of 'eval' $cpt->permit('entereval'); my $deparse = B::Deparse->new(); # prepend 'sub' so we have an anonymous sub later my $code_str = 'sub '.$deparse->coderef2text($s); # Seems to have no effect on behavior to remove package statements # $code_str =~ s/package \w+\;//g; print "DEPARSED $code_str\n"; my $result = $cpt->reval($parsed); die $@ if $@; $result->(); }
Output: "PACKAGE is main"

Many thanks, fever


In reply to Safe, namespaces, B::Deparse by djantzen

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.