conditional pragmas
authorIlya Zakharevich <ilya@math.berkeley.edu>
Mon, 31 Dec 2001 18:18:09 +0000 (13:18 -0500)
committerJarkko Hietaniemi <jhi@iki.fi>
Thu, 14 Feb 2002 21:54:43 +0000 (21:54 +0000)
Message-ID: <20011231181809.A29528@math.ohio-state.edu>

p4raw-id: //depot/perl@14694

MANIFEST
lib/if.pm [new file with mode: 0644]
lib/if.t [new file with mode: 0644]

index e464ac6..33ad2f6 100644 (file)
--- a/MANIFEST
+++ b/MANIFEST
@@ -1075,6 +1075,8 @@ lib/I18N/LangTags/ChangeLog       I18N::LangTags
 lib/I18N/LangTags/List.pm      List of tags for human languages
 lib/I18N/LangTags/README       I18N::LangTags
 lib/I18N/LangTags/test.pl      See if I18N::LangTags works
+lib/if.pm                      For "use if"
+lib/if.t                       Tests for "use if"
 lib/importenv.pl               Perl routine to get environment into variables
 lib/integer.pm                 For "use integer"
 lib/integer.t                  For "use integer" testing
diff --git a/lib/if.pm b/lib/if.pm
new file mode 100644 (file)
index 0000000..32c4fad
--- /dev/null
+++ b/lib/if.pm
@@ -0,0 +1,48 @@
+package if;
+
+our $VERSION = '0.01';
+
+sub work {
+  my $method = shift() ? 'import' : 'unimport';
+  return unless shift;         # CONDITION
+  my $p = shift;               # PACKAGE
+  eval "require $p" or die;    # Adds .pm etc if needed
+  $p->$method(@_) if $p->can($method);
+}
+
+sub import   { shift; unshift @_, 1; goto &work }
+sub unimport { shift; unshift @_, 0; goto &work }
+
+1;
+__END__
+
+=head1 NAME
+
+if - C<use> a Perl module if a condition holds
+
+=head1 SYNOPSIS
+
+  use if CONDITION, MODULE => ARGUMENTS;
+
+=head1 DESCRIPTION
+
+The construct
+
+  use if CONDITION, MODULE => ARGUMENTS;
+
+has no effect unless C<CONDITION> is true.  In this case the effect is
+the same as of
+
+  use MODULE ARGUMENTS;
+
+=head1 BUGS
+
+The current implementation does not allow specification of the
+required version of the module.
+
+=head1 AUTHOR
+
+Ilya Zakharevich L<mailto:perl-module-if@ilyaz.org>.
+
+=cut
+
diff --git a/lib/if.t b/lib/if.t
new file mode 100644 (file)
index 0000000..12ad0b0
--- /dev/null
+++ b/lib/if.t
@@ -0,0 +1,26 @@
+#!./perl
+
+BEGIN {
+    chdir 't' if -d 't';
+    @INC = '../lib';
+}
+
+use Test::More tests => 4;
+
+my $v_plus = $] + 1;
+my $v_minus = $] - 1;
+
+
+ok( eval "use if ($v_minus > \$]), strict => 'subs'; \${'f'} = 12" eq 12,
+    '"use if" with a false condition, fake pragma');
+
+ok( eval "use if ($v_minus > \$]), strict => 'refs'; \${'f'} = 12" eq 12,
+    '"use if" with a false condition and a pragma');
+
+ok( eval "use if ($v_plus > \$]), strict => 'subs'; \${'f'} = 12" eq 12,
+    '"use if" with a true condition, fake pragma');
+
+ok( (not defined eval "use if ($v_plus > \$]), strict => 'refs'; \${'f'} = 12"
+     and $@ =~ /while "strict refs" in use/),
+    '"use if" with a true condition and a pragma');
+