How can I use __DATA__ twice?

后端 未结 3 1280
耶瑟儿~
耶瑟儿~ 2020-12-25 12:09

How can I use __DATA__ twice?

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

while (  ) {
    print;
}

while (  ) {
           


        
3条回答
  •  生来不讨喜
    2020-12-25 13:02

    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 ();
    seek DATA, $data_start, 0;  # reposition the filehandle right past __DATA__
    print while ();
    

    See also:

    • tell
    • seek

提交回复
热议问题