loris has asked for the wisdom of the Perl Monks concerning the following question:

Hello all,

I am getting the LibXML error "Empty Stream". I suspect it has something to do with the fact that I am reading the XML from the __DATA__ block for a second time within the script.

Does anyone know if problems can arise if the __DATA__ block is read multiple times?

Thanks,

loris

  • Comment on "Empty Stream" error as result of repeated reading of __DATA__ block?

Replies are listed 'Best First'.
Re: "Empty Stream" error as result of repeated reading of __DATA__ block?
by gellyfish (Monsignor) on Aug 17, 2005 at 08:05 UTC

    Yes, if you want to read the from the DATA filehandle more than once you need to rewind it to the beginning. Something like:

    use Fcntl; + my $where = tell(DATA); while(<DATA>) { print; } + seek DATA, $where, SEEK_SET; + while(<DATA>) { print; } __DATA__ 1 2 3 4 5 6 7
    The reason you have to get the position of the filepointer in DATA with tell is that the DATA filehandle actually refers to the whole program file and is simply left at the beginning of the stuff after the __DATA__ after perl has finished reading in the program - thus if you do seek DATA, 0, SEEK_SET you will be at the start of the program text.

    /J\

      I might also point out that you must rewind regular files too in order to read from them again once you have reached EOF.

      Also I believe that use Fcntl ':seek'; will clear up your warning.

      Thanks very much, gellyfish, that was just what I needed.

      However, your code does produce a warning:

      Argument "SEEK_SET" isn't numeric in seek at ./test.pl line 13, <DATA> + line 7.

      on my system, which I don't understand, SEEK_SET being a constant after all. Do you know why this occurs?

      Thanks again,

      loris

        Er, no I don't know why this occurs - it is possible that you didn't use Fcntl and are not using strict. If you are worried by this you can use 0 instead but this is not guaranteed to be portable to all systems.

        /J\