简体   繁体   English

在Perl中,为什么不能将__DATA__用作可搜索的文件句柄?

[英]In Perl, why can't you use __DATA__ as a seekable filehandle?

Reading from DATA via the typical slurp works. 通过典型的slurp作品从DATA读取。 Trying to use DATA as a filehandle on which I can do a seek does not work. 尝试使用DATA作为我可以进行搜索的文件句柄是行不通的。 Is anyone able to point me the to the obvious mistake I must be making? 有人能够指出我必须犯的明显错误吗?

Code: 码:

#!/usr/bin/env perl

use strict;
use warnings;

if ($ARGV[0] eq 'seek' ) {
    my $log_fh = \*DATA;
    $log_fh->seek(64,0);
    print "\n-- 64 --\n",join ("", <$log_fh> );
} else {
    while (<DATA>) {
        print $_;
    }
}

exit;

__DATA__
01234567890123456789
1234567890123456789
1234567890123456789
12
X <- That X is the 64th char in
this file.
Y <- That Y is the 106th char in this file.
junk
more junk.
bye!

$ perl file_from_data.pl slurp
01234567890123456789
1234567890123456789
1234567890123456789
12
X <- That X is the 64th char in
this file.
Y <- That Y is the 106th char in this file.
junk
more junk.
bye!

Running the while() loop: 运行while()循环:

$ perl file_from_data.pl slurp
01234567890123456789
1234567890123456789
1234567890123456789
12
X <- That X is the 64th char in
this file.
Y <- That Y is the 106th char in this file.
junk
more junk.
bye!

Running the seek(), it appears to not start at DATA but the start of the script: 运行seek(),它似乎不是从DATA开始,而是脚本的开始:

$ perl file_from_data.pl seek

-- 64 --
'seek' ) {
    my $log_fh = \*DATA;
    $log_fh->seek(64,0);
    print "\n-- 64 --\n",join ("", <$log_fh> );
} else {
    while (<DATA>) {
        print $_;
    }
}

exit;

__DATA__
01234567890123456789
1234567890123456789
1234567890123456789
12
X <- That X is the 64th char in
this file.
Y <- That Y is the 106th char in this file.
junk
more junk.
bye!

This is an old Perl: 这是一个旧的Perl:

$ perl -v

This is perl 5, version 16, subversion 3 (v5.16.3) built for x86_64-linux- 
thread-multi

Running the seek(), it appears to not start at DATA but the start of the script 运行seek(),它似乎不是从DATA开始,而是从脚本的开始

I don't think you're making any mistake at all. 我认为你根本没有犯任何错误。 That's exactly what happens. 这正是发生的事情。 DATA is a filehandle that is open on your source file. DATA是在源文件上打开的文件句柄。 Before your first read() from that filehandle, the file pointer is positioned immediately after the __DATA__ token in the file. 在您从该文件句柄第一次read()之前,文件指针紧跟在文件中的__DATA__标记之后。 But you can use seek() to move the file pointer to any position at all in the file. 但是您可以使用seek()将文件指针移动到文件中的任何位置。

I guess it would be harder to implement a "special case" filehandle that wasn't able to move back before its initial position. 我想要实现一个无法在其初始位置之前移回的“特殊情况”文件句柄会更难。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM