我怎样才能使用 __DATA__ 两次? [英] How can I use __DATA__ twice?

查看:69
本文介绍了我怎样才能使用 __DATA__ 两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 __DATA__ 两次?

#!/usr/local/bin/perl
use warnings;
use 5.012;

while ( <DATA> ) {
    print;
}

while ( <DATA> ) {
    chomp if $. == 1;
    print scalar reverse;
    print "\n" if eof;
}

__DATA__
one
two
three
four
five
six

推荐答案

要使用 DATA 文件句柄两次,您需要倒带它.棘手的一点是,如果您执行 seek(DATA, 0, 0),它将定位到第一行源代码,而不是 __DATA__ 之后的行.因此,您需要先保存位置:

To use the DATA filehandle twice you need to rewind it. The tricky bit is that if you do seek(DATA, 0, 0), it'll be positioned to the first source line, not the line after __DATA__. Therefore you need to save the position first:

my $data_start = tell DATA; # save the position
print while (<DATA>);
seek DATA, $data_start, 0;  # reposition the filehandle right past __DATA__
print while (<DATA>);

另见:

这篇关于我怎样才能使用 __DATA__ 两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆