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}