Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

package and do

by esskar (Deacon)
on Feb 03, 2006 at 00:38 UTC ( #527511=perlquestion: print w/replies, xml ) Need Help??
esskar has asked for the wisdom of the Perl Monks concerning the following question:

my $foo = do { package Foo; local $/; <DATA>; };
works, reads the __DATA__ section in Foo and writes it to $foo
my $class = 'Bar'; my $bar = do { eval "package $bar"; local $/; <DATA>; };
does not work - probably because eval "package $bar" has its own scope.
Any ideas how i can solve my problem?

Replies are listed 'Best First'.
Re: package and do
by ikegami (Pope) on Feb 03, 2006 at 04:52 UTC
    The following is even simpler:
    my $pkg = 'Foo'; my $foo = do { local $/; eval "<${pkg}::DATA>" };

    The following is a version that doesn't use eval EXPR (faster, safer):

    my $pkg = 'Foo'; my $data_fh = do { no strict 'refs'; *{"${pkg}::DATA"} }; my $foo = do { local $/; <$data_fh> };

    And if you want to cut your memory usage in half, use the following:

    my $pkg = 'Foo'; my $data_fh; { no strict 'refs'; $data_fh = *{"${pkg}::DATA"}; } my $foo; { local $/; $foo = <$data_fh>; }

    You could even combine the two blocks.

Re: package and do
by reneeb (Chaplain) on Feb 03, 2006 at 00:59 UTC
    #!/usr/bin/perl use strict; use warnings; my $class = 'Foo'; my $foo = do{ eval "package $class; local \$/; <DATA>"}; print $foo; package Foo; __DATA__ Dies ist ein Test

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://527511]
Approved by planetscape
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2017-03-28 03:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Should Pluto Get Its Planethood Back?



    Results (326 votes). Check out past polls.