Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

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?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://527511]
Approved by planetscape
[jedikaiti]: Pretty!
[karlgoethebier]: jedikaiti: i just wanted to ask ;-)
[jedikaiti]: :-D

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (10)
As of 2017-07-20 15:55 GMT
Find Nodes?
    Voting Booth?
    I came, I saw, I ...

    Results (306 votes). Check out past polls.