¿Cómo puedo usar los DATOS dos veces?


¿Cómo puedo usar __DATA__ dos veces?

#!/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
Author: Brian Tompsett - 汤莱恩, 2010-12-16

2 answers

Para utilizar la DATA filehandle dos veces necesita rebobina. La parte complicada es que si haces seek(DATA, 0, 0), se posicionará en la primera línea de origen, no en la línea después de __DATA__. Por lo tanto, primero debe guardar la posición:

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

Véase también:

 45
Author: Eugene Yarmash,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-14 16:01:20

Puede usar el módulo Data::Handle para hacer el tell()ing y seek() ing para usted detrás de las escenas. (Aunque creo que si tiene perl 5.10 o posterior, puede dup el controlador de archivo DATA en lugar de compartir el controlador de archivo DATA original y buscar de un lado a otro en él.)

 7
Author: John Siracusa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-19 02:49:13