3

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?

Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265
Richlv
  • 3,954
  • 1
  • 17
  • 21
  • 1
    You need to `use My::Testing;` in your test file. Then call it as My::Testing::testme(). Otherwise look into perldoc Exporter, – xxfelixxx Oct 12 '15 at 06:51
  • 3
    xxfelixxx: He does _not_ need to `use My::Testing` unless he wants to read in a file named `My/Testing.pm` from a Perl library directory found in `@INC`. His code is in a file named `testme.pl`, so `use` won't work with it, and he's already loaded it with `require` (well, `require_ok`), so its contents are already accessible. – Dave Sherohman Oct 12 '15 at 07:48

1 Answers1

8

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

Dave Sherohman
  • 45,363
  • 14
  • 64
  • 102