Reputation: 27222
I'm trying to read some tgz data from the __END__
section of a perl script.
I'm running into problem with the filehandle, sometimes using it doesn't cause a problem and sometimes the script throws an error.
Here's some example code, I know the data isn't tgz but it does show the problem.)
#!/usr/bin/env perl
use strict;
use warnings;
my $raw_time = (stat(DATA))[9];
my $size = -s DATA;
my $kilosize = int($size / 1024) . 'k';
print "<P>Script size is $kilosize at $raw_time\n";
#print ref(DATA); #UNCOMMENT TO SEE THE PROBLEM?
__DATA__
DO NOT REMOVE THE PRECEDING LINE.
Everything else in this file will be ignored.
If I run this script I get
$ /tmp/data.pl
<P>Script size is 0k at 1500655490
DATA seems OK to use.
But, if I uncomment print ref(DATA);
I get an error on that line:
Bareword "DATA" not allowed while "strict subs" in use at /tmp/data.pl line 12.
Execution of /tmp/data.pl aborted due to compilation errors.
Why isn't the use of DATA earlier also a problem?
[pre-post update] If I change the line to be
print "ref:". ref(\*DATA);
It doesn't throw the compile error. What's going on?
Upvotes: 0
Views: 798
Reputation: 118138
Others have explained what's going on. In contexts where perl
expects a filehandle/fileglob, it is OK to use DATA
. But, in a context, such as ref(DATA)
where there is no a priori reason to assume that the argument is a file handle/glob, that does not work.
is there a lexical filehandle solution for
DATA
?
I am not quite sure what you are after, but this might help:
#!/usr/bin/env perl
use strict;
use warnings;
# You could use any variable name you like
my $DATA_FH;
CHECK { $DATA_FH = \*DATA }
print <$DATA_FH>
__DATA__
One
Upvotes: 4