The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

maybe - Use a Perl module and ignore error if can't be loaded

SYNOPSIS

  use Getopt::Long;
  use maybe 'Getopt::Long::Descriptive';
  if (maybe::HAVE_GETOPT_LONG_DESCRIPTIVE) {
    Getopt::Long::Descriptive::describe_options("usage: %c %o", @options);
  }
  else {
    Getopt::Long::GetOptions(\%options, @$opt_spec);
  }

  use maybe 'Carp' => 'confess';
  if (maybe::HAVE_CARP) {
    confess("Bum!");
  }
  else {
    die("Bum!");
  }

DESCRIPTION

This pragma loads a Perl module. If the module can't be loaded, the error will be ignored. Otherwise, the module's import method is called with unchanged caller stack.

The special constant maybe::HAVE_MODULE is created and it can be used to enable or disable block of code at compile time.

USAGE

use maybe Module;

It is exactly equivalent to

  BEGIN { eval { require Module; }; Module->import; }

except that Module must be a quoted string.

use maybe Module => LIST;

It is exactly equivalent to

  BEGIN { eval { require Module; }; Module->import( LIST ); }
use maybe Module => version, LIST;

It is exactly equivalent to

  BEGIN { eval { require Module; Module->VERSION(version); } Module->import( LIST ); }
use maybe Module => '';

If the LIST contains only one empty string, it is exactly equivalent to

  BEGIN { eval { require Module; }; }

CONSTANTS

HAVE_MODULE

This constant is set after trying to load the module. The name of constant is created from uppercased module name. The "::" string and any non-alphanumeric character is replaced with underscore. The constant contains the true value if the module was loaded or false value otherwise.

  use maybe 'File::Spec::Win32';
  return unless maybe::HAVE_FILE_SPEC_WIN32;

As any constant value it can be used to enable or disable the block code at compile time.

  if (maybe::HAVE_FILE_SPEC_WIN32) {
      # This block is compiled only if File::Spec::Win32 was loaded
      do_something;
  }

SEE ALSO

if, all, first.

BUGS

The Perl doesn't clean up the module if it wasn't loaded to the end, i.e. because of syntax error.

The name of constant could be the same for different modules, i.e. "Module", "module" and "MODULE" generate maybe::HAVE_MODULE constant.

If you find the bug or want to implement new features, please report it at http://rt.cpan.org/NoAuth/Bugs.html?Dist=maybe

AUTHOR

Piotr Roszatycki <dexter@cpan.org>

COPYRIGHT

Copyright (C) 2008, 2009 by Piotr Roszatycki <dexter@cpan.org>.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

See http://www.perl.com/perl/misc/Artistic.html