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

Re: __DATA__ used in BEGIN

by shmem (Chancellor)
on Nov 06, 2007 at 12:08 UTC ( [id://649194]=note: print w/replies, xml ) Need Help??


in reply to __DATA__ used in BEGIN

As moritz pointed out, BEGIN blocks are executed at compile time, so the rest of the file is not known at that time. So, no __DATA__ token has been seen yet, and its filehandle can't be opened.

If you absolutely need __DATA__ in a BEGIN block, you have to roll your own __DATA__ handling (opening and positioning, i.e. skipping all until the __DATA__ token):

package Foo::Bar::Quux; print "now in runtime...\n"; BEGIN { (my $package = __PACKAGE__) =~ s!::!/!g; my $file = $INC{$package.'.pm'}; open DATA , '<', $file or die "Can't open '$file': $!\n"; my $data = 0; while (<DATA>) { /^__DATA__$/ and $data = 1 and next; next unless $data; print "DATA: $_"; }; } 1; __DATA__ foo bar quux now in runtime... now in main
qwurx [shmem] ~ > perl -e 'print "now in main\n"; use Foo::Bar::Quux' DATA: foo DATA: bar DATA: quux now in runtime...

That's for a module. In a script, you would open $0.

--shmem

_($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                              /\_¯/(q    /
----------------------------  \__(m.====·.(_("always off the crowd"))."·
");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}

Replies are listed 'Best First'.
Re^2: __DATA__ used in BEGIN
by ikegami (Patriarch) on Nov 06, 2007 at 12:36 UTC
    Using a heredoc would have the same effect with less magic, although the code layout would be different.
    print "now in runtime...\n"; BEGIN { open my $fh , '<', \<<'__EOI__' or die; foo bar quux now in runtime... now in main __EOI__ while (<$fh>) { print "DATA: $_"; } } ...

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://649194]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2024-04-19 20:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found