home *** CD-ROM | disk | FTP | other *** search
/ CD Actual Thematic 7: Programming / CDAT7.iso / Share / Editores / Perl5 / perl / lib / site / Alias.pm next >
Encoding:
Perl POD Document  |  1997-08-10  |  10.7 KB  |  371 lines

  1. #
  2. # Documentation at the __END__
  3. #
  4.  
  5. package Alias;
  6.  
  7. require 5.003;
  8. require Exporter;
  9. require DynaLoader;
  10.  
  11. @ISA = qw(Exporter DynaLoader);
  12. @EXPORT = qw(alias attr);
  13. @EXPORT_OK = qw(const);
  14.  
  15. $VERSION = $VERSION = '2.3';
  16.  
  17. use Carp;
  18.  
  19. bootstrap Alias;
  20.  
  21. $Alias::KeyFilter = "";
  22. $Alias::AttrPrefix = "";
  23. $Alias::Deref = "";            # don't deref objects
  24.  
  25. sub alias {
  26.   croak "Need even number of args" if @_ % 2;
  27.   my($pkg) = caller;              # for namespace soundness
  28.   while (@_) {
  29.     # *foo = \*bar works in 5.002
  30.     *{"$pkg\:\:$_[0]"} = (defined($_[1]) and ref($_[1])) ? $_[1] : \$_[1];
  31.     shift; shift;
  32.   }
  33. }
  34.  
  35. # alias the elements of hashref
  36. # same as alias %{$_[0]}, but also localizes the aliases and
  37. # returns the hashref
  38. sub attr;
  39.  
  40. alias const => \&alias;           # alias the alias :-)
  41.  
  42.  
  43. 1;
  44. __END__
  45.  
  46. =head1 NAME
  47.  
  48. alias - declare symbolic aliases for perl data
  49.  
  50. attr  - auto-declare hash attributes for convenient access
  51.  
  52. const - define compile-time scalar constants
  53.  
  54.  
  55. =head1 SYNOPSIS
  56.  
  57.     use Alias qw(alias const attr);
  58.     alias TEN => $ten, Ten => \$ten, Ten => \&ten,
  59.           Ten => \@ten, Ten => \%ten, TeN => \*ten;
  60.     {
  61.        local @Ten;
  62.        my $ten = [1..10];
  63.        alias Ten => $ten;   # local @Ten
  64.     }
  65.  
  66.     const pi => 3.14, ten => 10;
  67.  
  68.     package Foo;
  69.     use Alias;
  70.     sub new { bless {foo => 1, _bar => [2, 3]}, $_[0] }
  71.     sub a_method {
  72.        my $s = attr shift;
  73.        # $foo, @_bar are now local aliases for
  74.        # $_[0]{foo}, @{$_[0]{_bar}} etc.
  75.     }
  76.  
  77.     sub b_method {
  78.       local $Alias::KeyFilter = "_";
  79.       local $Alias::AttrPrefix = "main::";
  80.       my $s = attr shift;
  81.       # local @::_bar is now available, ($foo, $::foo are not)
  82.     }
  83.  
  84.     sub c_method {
  85.       local $Alias::KeyFilter = sub { $_ = shift; return (/^_/ ? 1 : 0) };
  86.       local $Alias::AttrPrefix = sub {
  87.                                        $_ = shift;
  88.                        s/^_(.+)$/main::$1/;
  89.                        return $_
  90.                      };
  91.       my $s = attr shift;
  92.       # local @::bar is now available, ($foo, $::foo are not)
  93.     }
  94.  
  95.  
  96. =head1 DESCRIPTION
  97.  
  98. Provides general mechanisms for aliasing perl data for convenient access.
  99.  
  100. This module works by putting some values on the symbol table with
  101. user-supplied names.  Values that are references will get dereferenced into
  102. their base types.  This means that a value of C<[1,2,3]> with a name of
  103. "foo" will be made available as C<@foo>, not C<$foo>.
  104.  
  105. The exception to this rule is the default behavior of the C<attr> function,
  106. which will not dereference values which are blessed references (aka
  107. objects).  See L<$Alias::Deref> for how to change this default behavior.
  108.  
  109. =head2 Functions
  110.  
  111. =over 4
  112.  
  113. =item alias
  114.  
  115. Given a list of name => value pairs, declares aliases
  116. in the C<caller>s namespace. If the value supplied is a reference, the
  117. alias is created for the underlying value instead of the reference
  118. itself (there is no need to use this module to alias references--they
  119. are automatically "aliased" on assignment).  This allows the user to
  120. alias most of the basic types.
  121.  
  122. If the value supplied is a scalar compile-time constant, the aliases 
  123. become read-only. Any attempt to write to them will fail with a run time
  124. error. 
  125.  
  126. Aliases can be dynamically scoped by pre-declaring the target variable as
  127. C<local>.  Using C<attr> for this purpose is more convenient, and
  128. recommended.
  129.  
  130. =item attr
  131.  
  132. Given a hash reference, aliases the values of the hash to the names that
  133. correspond to the keys.  It always returns the supplied value.  The aliases
  134. are local to the enclosing block. If any of the values are unblessed
  135. references, they are available as their dereferenced types.  Thus the action
  136. is similar to saying:
  137.  
  138.     alias %{$_[0]}
  139.  
  140. but, in addition, also localizes the aliases, and does not dereference
  141. objects.  Dereferencing of objects can be forced by setting the C<Deref>
  142. option.  See L<$Alias::Deref>.
  143.  
  144. This can be used for convenient access to hash values and hash-based object
  145. attributes.  
  146.  
  147. Note that this makes available the semantics of C<local> subroutines and
  148. methods.  That makes for some nifty possibilities.  We could make truly
  149. private methods by putting anonymous subs within an object.  These subs
  150. would be available within methods where we use C<attr>, and will not
  151. be visible to the outside world as normal methods.  We could forbid 
  152. recursion in methods by always putting an empty sub in the object hash 
  153. with the same key as the method name. This would be useful where a method 
  154. has to run code from other modules, but cannot be certain whether that 
  155. module will call it back again.
  156.  
  157. The default behavior is to create aliases for all the entries in the hash,
  158. in the callers namespace.  This can be controlled by setting a few options.
  159. See L<Configuration Variables> for details.
  160.  
  161. =item const
  162.  
  163. This is simply a function alias for C<alias>, described above.  Provided on
  164. demand at C<use> time, since it reads better for constant declarations.
  165. Note that hashes and arrays cannot be so C<const>rained.
  166.  
  167. =back
  168.  
  169. =head2 Configuration Variables
  170.  
  171. The following configuration variables can be used to control the behavior of
  172. the C<attr> function.  They are typically set after the C<use Alias;>
  173. statement.  Another typical usage is to C<local>ize them in a block so that
  174. their values are only effective within that block.
  175.  
  176. =over 4
  177.  
  178. =item $Alias::KeyFilter
  179.  
  180. Specifies the key prefix used for determining which hash entries will be
  181. interned by C<attr>.  Can be a CODE reference, in which case it will be
  182. called with the key, and the boolean return value will determine if
  183. that hash entry is a candidate attribute.
  184.  
  185. =item $Alias::AttrPrefix
  186.  
  187. Specifies a prefix to prepend to the names of localized attributes created
  188. by C<attr>.  Can be a CODE reference, in which case it will be called with
  189. the key, and the result will determine the full name of the attribute.  The
  190. value can have embedded package delimiters ("::" or "'"), which cause the
  191. attributes to be interned in that namespace instead of the C<caller>s own
  192. namespace. For example, setting it to "main::" makes C<use strict 'vars';>
  193. somewhat more palatable (since we can refer to the attributes as C<$::foo>,
  194. etc., without actually declaring the attributes).
  195.  
  196. =item $Alias::Deref
  197.  
  198. Controls the implicit dereferencing behavior of C<attr>.  If it is set to
  199. "" or 0, C<attr> will not dereference blessed references.  If it is a true
  200. value (anything but "", 0, or a CODE reference), all references will be
  201. made available as their dereferenced types, including values that may be
  202. objects.  The default is "".
  203.  
  204. This option can be used as a filter if it is set to a CODE reference, in
  205. which case it will be called with the key and the value (whenever the value
  206. happens to be a reference), and the boolean return value will determine if
  207. that particular reference must be dereferenced.
  208.  
  209.  
  210. =back
  211.  
  212. =head2 Exports
  213.  
  214. =over 4
  215.  
  216. =item alias
  217.  
  218. =item attr
  219.  
  220. =back
  221.  
  222. =head1 EXAMPLES
  223.  
  224. Run these code snippets and observe the results to become more familiar
  225. with the features of this module.
  226.  
  227.     use Alias qw(alias const attr);
  228.     $ten = 10;
  229.     alias TEN => $ten, Ten => \$ten, Ten => \&ten,
  230.           Ten => \@ten, Ten => \%ten;
  231.     alias TeN => \*ten;  # same as *TeN = *ten
  232.  
  233.     # aliasing basic types
  234.     $ten = 20;   
  235.     print "$TEN|$Ten|$ten\n";   # should print "20|20|20"
  236.     sub ten { print "10\n"; }
  237.     @ten = (1..10);
  238.     %ten = (a..j);
  239.     &Ten;                       # should print "10"
  240.     print @Ten, "|", %Ten, "\n";
  241.  
  242.     # this will fail at run time
  243.     const _TEN_ => 10;
  244.     eval { $_TEN_ = 20 };
  245.     print $@ if $@;
  246.  
  247.     # dynamically scoped aliases
  248.     @DYNAMIC = qw(m n o);
  249.     {
  250.        my $tmp = [ qw(a b c d) ];
  251.        local @DYNAMIC;
  252.        alias DYNAMIC => $tmp, PERM => $tmp;
  253.  
  254.        $DYNAMIC[2] = 'zzz';
  255.        # prints "abzzzd|abzzzd|abzzzd"
  256.        print @$tmp, "|", @DYNAMIC, "|", @PERM, "\n";
  257.  
  258.        @DYNAMIC = qw(p q r);
  259.        # prints "pqr|pqr|pqr"
  260.        print @$tmp, "|", @DYNAMIC, "|", @PERM, "\n";
  261.     }
  262.  
  263.     # prints "mno|pqr"
  264.     print @DYNAMIC, "|", @PERM, "\n";
  265.  
  266.     # named closures
  267.     my($lex) = 'abcd';
  268.     $closure = sub { print $lex, "\n" };
  269.     alias NAMEDCLOSURE => \&$closure;
  270.     NAMEDCLOSURE();            # prints "abcd"
  271.     $lex = 'pqrs';
  272.     NAMEDCLOSURE();            # prints "pqrs"
  273.  
  274.     # hash/object attributes
  275.     package Foo;
  276.     use Alias;
  277.     sub new { 
  278.       bless 
  279.     { foo => 1, 
  280.           bar => [2,3], 
  281.           buz => { a => 4},
  282.           privmeth => sub { "private" },
  283.           easymeth => sub { die "to recurse or to die, is the question" },
  284.         }, $_[0]; 
  285.     }
  286.  
  287.     sub easymeth {
  288.       my $s = attr shift;    # localizes $foo, @bar, %buz etc with values
  289.       eval { $s->easymeth }; # should fail
  290.       print $@ if $@;
  291.  
  292.       # prints "1|2|3|a|4|private|"
  293.       print join '|', $foo, @bar, %buz, $s->privmeth, "\n";
  294.     }
  295.  
  296.     $foo = 6;
  297.     @bar = (7,8);
  298.     %buz = (b => 9);
  299.     Foo->new->easymeth;       # this will not recurse endlessly
  300.  
  301.     # prints "6|7|8|b|9|"
  302.     print join '|', $foo, @bar, %buz, "\n";
  303.  
  304.     # this should fail at run-time
  305.     eval { Foo->new->privmeth };
  306.     print $@ if $@;
  307.  
  308.  
  309. =head1 NOTES
  310.  
  311. It is worth repeating that the aliases created by C<alias> and C<const> will
  312. be created in the C<caller>s namespace (we can use the C<AttrPrefix> option to
  313. specify a different namespace for C<attr>).  If that namespace happens to be
  314. C<local>ized, the aliases created will be local to that block.  C<attr>
  315. localizes the aliases for us.
  316.  
  317. Remember that references will be available as their dereferenced types.
  318.  
  319. Aliases cannot be lexical, since, by neccessity, they live on the
  320. symbol table. 
  321.  
  322. Lexicals can be aliased. Note that this provides a means of reversing the
  323. action of anonymous type generators C<\>, C<[]> and C<{}>.  This allows us
  324. to anonymously construct data or code and give it a symbol-table presence
  325. when we choose.
  326.  
  327. Any occurrence of C<::> or C<'> in names will be treated as package
  328. qualifiers, and the value will be interned in that namespace.
  329.  
  330. Remember that aliases are very much like references, only we don't
  331. have to dereference them as often.  Which means we won't have to
  332. pound on the dollars so much.
  333.  
  334. We can dynamically make subroutines and named closures with this scheme.
  335.  
  336. It is possible to alias packages, but that might be construed as
  337. abuse.
  338.  
  339. Using this module will dramatically reduce noise characters in 
  340. object-oriented perl code.
  341.  
  342.  
  343. =head1 BUGS
  344.  
  345. C<use strict 'vars';> is not very usable, since we B<depend> so much
  346. on the symbol table.  You can declare the attributes with C<use vars> to
  347. avoid warnings.  Setting C<$Alias::AttrPrefix> to "main::" is one way
  348. to avoid C<use vars> and frustration.
  349.  
  350. Tied variables cannot be aliased properly, yet.
  351.  
  352.  
  353. =head1 VERSION
  354.  
  355. Version 2.2       1 December 1996
  356.  
  357.  
  358. =head1 AUTHOR
  359.  
  360. Gurusamy Sarathy                gsar@umich.edu
  361.  
  362. Copyright (c) 1995-97 Gurusamy Sarathy. All rights reserved.
  363. This program is free software; you can redistribute it and/or
  364. modify it under the same terms as Perl itself.
  365.  
  366. =head1 SEE ALSO
  367.  
  368. perl(1)
  369.  
  370. =cut
  371.