http://qs1969.pair.com?node_id=527511

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 (Patriarch) 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