Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
559 views
in Technique[技术] by (71.8m points)

perl - How can I use __DATA__ twice?

How can I use __DATA__ twice?

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

while ( <DATA> ) {
    print;
}

while ( <DATA> ) {
    chomp if $. == 1;
    print scalar reverse;
    print "
" if eof;
}
__DATA__
one
two
three
four
five
six
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>);

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...