princepawn has asked for the wisdom of the Perl Monks concerning the following question:

I think there should be some non-regex way of getting the package of the code I evaluate, ie:
my $retval = eval $source; warn $retval->package; # prints package of evaluated # source
why you ask? just look at this. I would rather not maintain this regex:
my $code = join( '', <$fh> ); close( $fh ); eval $code; if ( $@ ) { $r->log_error( $@ ); return SERVER_ERROR; } my $package = ($code =~ /^\s*package\s+([\w:]+);/m)[0];

Replies are listed 'Best First'.
Re: Getting the package of evaluated source code:
by maverick (Curate) on Aug 26, 2001 at 22:01 UTC
    package Foo; sub get_package { return __PACKAGE__; } 1;
    Try this :)

    Update: hmmm..if the compilation of the code fails, I can't get seem to get hold of it any other way than what you already have.

    Update 2:Possible solution. If the code you're trying to pick up is always a package of some sort, you could re-arrange your logic like

    package Foo; sub do_something { print __PACKAGE__,"\n"; } 1; -------------------------------- foreach ("Foo.pm") { eval { require $_; }; if ($@) { print "Error in $_\n"; print $@,"\n"; } } Foo::do_something();

    /\/\averick
    perl -l -e "eval pack('h*','072796e6470272f2c5f2c5166756279636b672');"

Re (tilly) 1: Getting the package of evaluated source code:
by tilly (Archbishop) on Aug 27, 2001 at 08:17 UTC
    There should be? Why should there be?

    Suppose that what you are evaling has multiple package statements? What package does the overall thing have? Does the question even make sense?

    Your regex doesn't handle this. Nor does it handle the case where the code has no package statement in it. (In which case you get your current package.)

    Instead I would ask why you want to know what package the external code has, and solve that problem directly.