Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

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
[MidLifeXis]: How many languages would that 'Ex' alias handle. ETOOCUTE
[choroba]: I don't believe modules with syntax errors in Synopsis

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (11)
As of 2017-02-27 11:50 GMT
Find Nodes?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?

    Results (383 votes). Check out past polls.