in reply to Using guards for script execution?
This code is a weird formulation because the file that contains main() will always be executed as a main program? Normal practice would be to do away with this extra level of indentation implied by the subroutine main and just start writing the "main" code. The unless (caller){} does nothing useful. You could have just put a simple main(); instead to call the sub main.sub main { print "Hello, world!\n"; } unless (caller) { main; }
I attach demomain.pl and demo.pm below.
Note that demomain.pl could have been called "demo.pl", but I didn't want to confuse you.
Anyway note that you can have a .pm file of the same name as a .pl file.
In my demo.pm file, I use caller(), test() if !caller;. If demo.pm is being run as a main program, test() will execute. If demo.pm is being "used" by another program, say by demomain.pl, all of the top-level code in demo.pm will run, but test() will not run because Perl knows that demo.pm is not being run as a main program. There is no need to so something similar in your main.pl program because your main is always a main program!
This provides a very "lightweight" test framework. There are such things as .t files which are used in more complicated situations.
It is possible to split a main program across multiple files, i.e., same package in multiple files. I don't demo that because I think it is a very bad idea.
#!/usr/bin/perl # File: demo.pl use strict; use warnings; $|=1; # turn off buffering use Demo qw(example); # test() is not exported by Demo.pl # this the error produced... # Undefined subroutine &main::test called at C:\Projects_Perl\testing\ +demo.pl line 7. # my $x = test(); my $y = Demo::test(); #this is ok , Fully qualified name print "test() returned $y\n"; __END__ Prints: top level in Demo.pm this is the test subroutine! test() returned 1
#!/usr/bin/perl # File: Demo.pm use strict; use warnings; package Demo; use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $VERSION); use Exporter; our $VERSION=1.01; our @ISA = qw(Exporter); our @EXPORT = qw(); our @EXPORT_OK = qw(example); our $DEBUG =0; test() if !caller; # runs test() if run as a "main program" sub test { print "this is the test subroutine!\n"; return 1;} sub example {return "this is an example"}; print "top level in Demo.pm\n"; 1;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Using guards for script execution? (testing)
by tye (Sage) on Mar 01, 2017 at 16:18 UTC | |
by Anonymous Monk on Mar 01, 2017 at 17:58 UTC | |
by Your Mother (Archbishop) on Mar 01, 2017 at 23:41 UTC |