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

Hi, I understand that the standard convention is to put the test case in a separate file under the "t/" directory, but is it possible to put the testing code in the same file? sort of like "main" in java, or the qq/if __name__ == "__main__"/ trick in python? I was trying to do the follwoing:
# file Foo.pm package Foo; sub foo{ print "foo called\n"; } # the following are testing code package main; Foo::foo(); 1;
which I can then run "perl Foo.pm", but I can't "use" it in other scripts because the "main" section will get executed. I guess one way to ask is whether a package can know how it is used? Thanks

Replies are listed 'Best First'.
Re: Modules containing test code in the same file
by BrowserUk (Patriarch) on Jan 07, 2005 at 09:01 UTC

    package Foo; ... return 1 if caller; package main; my $test = Foo->new(...); ...

    Examine what is said, not who speaks.
    Silence betokens consent.
    Love the truth but pardon error.
Re: Modules containing test code in the same file
by eyepopslikeamosquito (Archbishop) on Jan 07, 2005 at 09:20 UTC
Re: Modules containing test code in the same file
by dimar (Curate) on Jan 07, 2005 at 17:31 UTC

    If you do not have access to one of the better alternatives like Test::Inline, you can do the same kind of trick they do in python-land by evaluating the special variables $0 and __FILE__.

    ### begin_: file metadata ### <region-file_info> ### main: ### - name: trySelfTestModule ### desc: perl module w/ test script inside ### </region-file_info> ### begin_: init perl package trySelfTestModule; use strict; use warnings; use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $VERSION); use Exporter; $VERSION = 1.00; @ISA = qw(Exporter); @EXPORT = qw( ); ### begin_: test code ### test_: run this test iff this package ### is being run directly. We check to ### make sure the special variable $0 is ### equal to __FILE__ special variable if($0 eq __FILE__ ){ print trySelfTestModule::SayHello(); }; if($0 eq __FILE__ ){ print trySelfTestModule::SayByeBye(); }; ###end_test ### begin_: subroutine code push @EXPORT_OK, qw( SayHello ); sub SayHello { return "Hello World\n"; }###end_sub push @EXPORT_OK, qw( SayByeBye ); sub SayByeBye { return "ByeBye World\n"; }###end_sub ### begin_: end perl 1; __END__