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 "\n" if eof;
}
__DATA__
one
two
three
four
five
six

Answers


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:


You can use the Data::Handle module to do the tell()ing and seek()ing for you behind the scenes. (Though I believe if you have perl 5.10 or later you can dup the DATA file handle instead of sharing the original DATA file handle and seeking back and forth in it.)


In all honesty, the easiest solution is to read DATA once and stash it in an array or variable.

my @data;
while(<DATA>){
  push @data, $_;
}

Need Your Help

Filtering out log4j messages from third-party frameworks?

java hibernate spring log4j

How do I filter log messages from external third party frameworks? I am using Hibernate and Spring framework and I would like to suppress the logs so that only my log4j logs appears.

C++ a member with an in-class initializer must be const

c++ visual-studio-2010

I am trying to create a static string in my class: (in my header file)