1package if; 2 3$VERSION = '0.0603'; 4 5sub work { 6 my $method = shift() ? 'import' : 'unimport'; 7 die "Too few arguments to 'use if' (some code returning an empty list in list context?)" 8 unless @_ >= 2; 9 return unless shift; # CONDITION 10 11 my $p = $_[0]; # PACKAGE 12 (my $file = "$p.pm") =~ s!::!/!g; 13 require $file; # Works even if $_[0] is a keyword (like open) 14 my $m = $p->can($method); 15 goto &$m if $m; 16} 17 18sub import { shift; unshift @_, 1; goto &work } 19sub unimport { shift; unshift @_, 0; goto &work } 20 211; 22__END__ 23 24=head1 NAME 25 26if - C<use> a Perl module if a condition holds 27 28=head1 SYNOPSIS 29 30 use if CONDITION, MODULE => ARGUMENTS; 31 32=head1 DESCRIPTION 33 34The C<if> module is used to conditionally load another module. 35The construct 36 37 use if CONDITION, MODULE => ARGUMENTS; 38 39will load MODULE only if CONDITION evaluates to true. 40The above statement has no effect unless C<CONDITION> is true. 41If the CONDITION does evaluate to true, then the above line has 42the same effect as: 43 44 use MODULE ARGUMENTS; 45 46The use of C<< => >> above provides necessary quoting of C<MODULE>. 47If you don't use the fat comma (eg you don't have any ARGUMENTS), 48then you'll need to quote the MODULE. 49 50=head2 EXAMPLES 51 52The following line is taken from the testsuite for L<File::Map>: 53 54 use if $^O ne 'MSWin32', POSIX => qw/setlocale LC_ALL/; 55 56If run on any operating system other than Windows, 57this will import the functions C<setlocale> and C<LC_ALL> from L<POSIX>. 58On Windows it does nothing. 59 60The following is used to L<deprecate> core modules beyond a certain version of Perl: 61 62 use if $] > 5.016, 'deprecate'; 63 64This line is taken from L<Text::Soundex> 3.04, 65and marks it as deprecated beyond Perl 5.16. 66If you C<use Text::Soundex> in Perl 5.18, for example, 67and you have used L<warnings>, 68then you'll get a warning message 69(the deprecate module looks to see whether the 70calling module was C<use>'d from a core library directory, 71and if so, generates a warning), 72unless you've installed a more recent version of L<Text::Soundex> from CPAN. 73 74=head1 BUGS 75 76The current implementation does not allow specification of the 77required version of the module. 78 79=head1 SEE ALSO 80 81L<Module::Requires> can be used to conditionally load one or modules, 82with constraints based on the version of the module. 83Unlike C<if> though, L<Module::Requires> is not a core module. 84 85L<Module::Load::Conditional> provides a number of functions you can use to 86query what modules are available, and then load one or more of them at runtime. 87 88L<provide> can be used to select one of several possible modules to load, 89based on what version of Perl is running. 90 91=head1 AUTHOR 92 93Ilya Zakharevich L<mailto:ilyaz@cpan.org>. 94 95=cut 96 97