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

Can a function in a module read the __DATA__ of the calling program?

I have a module which contains a function that reads a filehandle, $fh.

I'd like to write a test which tests that function. To do that, I need to provide it some sample data. I figured I would just drop a few lines into the __DATA__ section of the testing program, then point $fh at the *DATA handle and test away.

Unfortunately, it doesn't seem to work.

Here's what I'm trying (more or less):

In test.pl:

$fh = *DATA; my $results = $app->process(); is ( $results->{item1}, "result1", "process item1" ); __DATA__ item1,data1 item2,data2 item3,data3

In Module.pm:

use vars qw($fh); sub process { my ($self) = @_; my $reslts = {}; while (<$fh>) { [do stuff] $results->{$key} = $result; } return $results; }

What basic bit of idiocy am I committing this time? :-)

Wally Hartshorn

Replies are listed 'Best First'.
Re: Problem Reading __DATA__ in a Module
by blokhead (Monsignor) on Apr 13, 2004 at 00:52 UTC
    I'll assume there is more to test.pl and Module.pm, since you had to instantiate $app somehow)... In test.pl, $fh refers to (most likely) $main::fh, but in Module.pm, it probably refers to $Module::fh (assuming you have a package Module at the top). These are very much different variables.

    The million dollar question is, why are you using globals to pass data into a method? Either the filehandle should be an attribute encapsulated in the object, or something passed in explicitly to the method call. Or it could even be a static package variable, with access through a class method.

    If you really really really really want to "pass" data to your method this way, just call the variable by its fully-qualified name $Module::fh from test.pl.

    Update: Looking even more closely, you should have $fh = \*DATA (note the backslash). Although my previous suggestions still apply as well.

    blokhead

Re: Problem Reading __DATA__ in a Module
by stvn (Monsignor) on Apr 13, 2004 at 20:04 UTC

    One thing to note about reading the DATA filehandle. Once you have read it, its really tricky to read it again, unless you unload and reload the module. I have run into this is the past. You can just seek to the start of the filehandle or you end up at the top of the actual file (if i remember correctly). The best way to get around this of course is to make sure you read once and cache.

    -stvn