Beefy Boxes and Bandwidth Generously Provided by pair Networks Joe
We don't bite newbies here... much
 
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?

Comment on package and do
Select or Download Code
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
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.

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 the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (6)
As of 2014-04-20 00:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (485 votes), past polls