vars.pm 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package vars;
  2. use 5.006;
  3. our $VERSION = '1.03';
  4. use warnings::register;
  5. use strict qw(vars subs);
  6. sub import {
  7. my $callpack = caller;
  8. my (undef, @imports) = @_;
  9. my ($sym, $ch);
  10. foreach (@imports) {
  11. if (($ch, $sym) = /^([\$\@\%\*\&])(.+)/) {
  12. if ($sym =~ /\W/) {
  13. # time for a more-detailed check-up
  14. if ($sym =~ /^\w+[[{].*[]}]$/) {
  15. require Carp;
  16. Carp::croak("Can't declare individual elements of hash or array");
  17. } elsif (warnings::enabled() and length($sym) == 1 and $sym !~ tr/a-zA-Z//) {
  18. warnings::warn("No need to declare built-in vars");
  19. } elsif (($^H &= strict::bits('vars'))) {
  20. require Carp;
  21. Carp::croak("'$_' is not a valid variable name under strict vars");
  22. }
  23. }
  24. $sym = "${callpack}::$sym" unless $sym =~ /::/;
  25. *$sym =
  26. ( $ch eq "\$" ? \$$sym
  27. : $ch eq "\@" ? \@$sym
  28. : $ch eq "\%" ? \%$sym
  29. : $ch eq "\*" ? \*$sym
  30. : $ch eq "\&" ? \&$sym
  31. : do {
  32. require Carp;
  33. Carp::croak("'$_' is not a valid variable name");
  34. });
  35. } else {
  36. require Carp;
  37. Carp::croak("'$_' is not a valid variable name");
  38. }
  39. }
  40. };
  41. 1;
  42. __END__
  43. =head1 NAME
  44. vars - Perl pragma to predeclare global variable names
  45. =head1 SYNOPSIS
  46. use vars qw($frob @mung %seen);
  47. =head1 DESCRIPTION
  48. NOTE: For use with variables in the current package for a single scope, the
  49. functionality provided by this pragma has been superseded by C<our>
  50. declarations, available in Perl v5.6.0 or later, and use of this pragma is
  51. discouraged. See L<perlfunc/our>.
  52. This will predeclare all the variables whose names are
  53. in the list, allowing you to use them under "use strict", and
  54. disabling any typo warnings.
  55. Unlike pragmas that affect the C<$^H> hints variable, the C<use vars> and
  56. C<use subs> declarations are not BLOCK-scoped. They are thus effective
  57. for the entire file in which they appear. You may not rescind such
  58. declarations with C<no vars> or C<no subs>.
  59. Packages such as the B<AutoLoader> and B<SelfLoader> that delay
  60. loading of subroutines within packages can create problems with
  61. package lexicals defined using C<my()>. While the B<vars> pragma
  62. cannot duplicate the effect of package lexicals (total transparency
  63. outside of the package), it can act as an acceptable substitute by
  64. pre-declaring global symbols, ensuring their availability to the
  65. later-loaded routines.
  66. See L<perlmodlib/Pragmatic Modules>.
  67. =cut