[Israel.pm] A Perl 5 Gotcha

Gaal Yahas gaal at forum2.org
Sun Mar 8 05:50:36 PDT 2009

It's not essential here. if !caller is just a trick/convention you can
use to support making everything potentially a module and optionally
have an entry point in every module.

So for example, let's say you have a module that parses and transforms
files in some format, let's say XPM images. You write your code in a
style that lets it be called programmatcally, used by other people's
code. But you also want to supply a handy command-line interface. So
you do:

package XPM;

main() if !caller();
sub main {
  require Getopt::Long;
  Getopt::Long::GetOptions \my %cmdline,
    qw(help|h input|i=s output|o=s ........);

  my $xpm = XPM->new(.....);
  # whatever
  exit 0;

# And now comes your modular implementation of XPM.

As you further modularize your code (break it up into more .pm files),
you may choose to add more main functions that only make sense for
testing things, for example.

On Sun, Mar 8, 2009 at 11:44 AM, Offer Kaye <offer.kaye at gmail.com> wrote:
> On Fri, Mar 6, 2009 at 9:41 AM, Gaal Yahas wrote:
>> Another is near the top of the file to say:
>> main() if !caller;
>> sub main {
>>    # ...
>>    exit 0;
>> }
> By wrapping the main body of the file in a subroutine of itself you've
> restricted the scope of the (lexical) $filename to no longer be
> file-wide, thus causing a compilation error (vs. the previous run-time
> error) when $filename is called inside print_filename.
> This much I understand.
> But what does "if !caller" have to do with it?
> --
> Offer Kaye
> _______________________________________________
> Perl mailing list
> Perl at perl.org.il
> http://perl.org.il/mailman/listinfo/perl

Gaal Yahas <gaal at forum2.org>

More information about the Perl mailing list