Richlv
Richlv

Reputation: 4143

Why does 'package' keyword in Perl modulino break tests?

Let's say there's a simple Perl script testme.pl like this:

use strict;
use warnings;

sub testme {
        return 1;
}

1;

And a test file testme.t like this:

use strict;
use warnings;

use Test::More;
require_ok('testing.pl');
ok(testme());
done_testing();

Running perl testme.t seems to work as expected, but both http://www.perlmonks.org/bare/?node_id=537361 and https://stackoverflow.com/a/9134624/272387 suggest to add a package line, so I modify the original script to be:

use strict;
use warnings;
package My::Testing;

sub testme {
        return 1;
}

1;

Now the test fails with:

Undefined subroutine &main::testme called at testing.t

Why so?

Upvotes: 3

Views: 137

Answers (1)

Dave Sherohman
Dave Sherohman

Reputation: 46187

It fails because your testme sub is no longer in the default main namespace, it is now in the My::Testing namespace (package). You now need to access it by its full name, My::Testing::testme().

Identifiers in main don't need their package to be specified explicitly, since it's the default, but that's why the error message refers to it as main::testme.

(You could also use Exporter within the My::Testing package, export the sub, and then import it from your test script as a way of copying the sub into the test script's namespace. Or you could put another package My::Testing command into the test script, so that it will look in the My::Testing namespace by default. But referencing it as My::Testing::testme() is the simplest way to fix it and most clearly illustrates the reasoning behind the error message you're getting.)

Upvotes: 8

Related Questions