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

前端之家收集整理的这篇文章主要介绍了在Perl中,为什么不能将__DATA__用作可搜索的文件句柄?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
通过典型的slurp作品从DATA读取.尝试使用DATA作为我可以进行搜索文件句柄是行不通的.有人能够指出我必须犯的明显错误吗?

码:

#!/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!

运行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!

运行seek(),它似乎不是从DATA开始,而是脚本的开始:

$perl file_from_data.pl seek

-- 64 --
'seek' ) {
    my $log_fh = \*DATA;
    $log_fh->seek(64,<$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:

$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

我认为你根本没有犯任何错误.这正是发生的事情. DATA是在源文件上打开的文件句柄.在您从该文件句柄第一次读取()之前,文件指针紧跟在文件中的__DATA__标记之后.但是您可以使用seek()将文件指针移动到文件中的任何位置.

我想要实现一个无法在其初始位置之前移回的“特殊情况”文件句柄会更难.

猜你在找的Perl相关文章