File Coverage

lib/Data/Alias.pm
Criterion Covered Total %
statement 14 14 100.0
branch n/a
condition n/a
subroutine 5 5 100.0
pod n/a
total 19 19 100.0


line stmt bran cond sub pod time code
1             package Data::Alias;
2              
3 29     29   2065027 use 5.008001;
  29         369  
4              
5 29     29   166 use strict;
  29         51  
  29         580  
6 29     29   118 use warnings;
  29         52  
  29         1369  
7              
8             our $VERSION = '1.27';
9              
10 29     29   177 use base 'Exporter';
  29         68  
  29         5099  
11 29     29   189 use base 'DynaLoader';
  29         77  
  29         7366  
12              
13             our @EXPORT = qw(alias);
14             our @EXPORT_OK = qw(alias copy deref);
15             our %EXPORT_TAGS = (all => \@EXPORT_OK);
16              
17             bootstrap Data::Alias $VERSION;
18             pop our @ISA;
19              
20             =head1 NAME
21              
22             Data::Alias - Comprehensive set of aliasing operations
23              
24             =head1 SYNOPSIS
25              
26             use Data::Alias;
27              
28             alias {
29             # aliasing instead of copying whenever possible
30             };
31              
32             alias $x = $y; # alias $x to $y
33             alias @x = @y; # alias @x to @y
34             alias $x[0] = $y; # similar for array and hash elements
35             alias push @x, $y; # push alias to $y onto @x
36             $x = alias [ $y, $z ]; # construct array of aliases
37             alias my ($x, $y) = @_; # named aliases to arguments
38             alias { ($x, $y) = ($y, $x) }; # swap $x and $y
39             alias { my @t = @x; @x = @y; @y = @t }; # swap @x and @y
40              
41             use Data::Alias qw/ alias copy /;
42              
43             alias { copy $x = $y }; # force copying inside alias-BLOCK
44              
45             use Data::Alias qw/ deref /;
46              
47             my @refs = (\$x, \@y, \%z);
48             foo(deref @refs) # same as foo($x, @y, %z)
49              
50             =head1 DESCRIPTION
51              
52             Aliasing is the phenomenon where two different expressions actually refer to
53             the same thing. Modifying one will modify the other, and if you take a
54             reference to both, the two values are the same.
55              
56             Aliasing occurs in Perl for example in for-loops and sub-calls:
57              
58             for $var ($x) {
59             # here $var is an alias to $x
60             }
61              
62             foo($y);
63             sub foo {
64             # here $_[0] is an alias to $y
65             }
66              
67             Data::Alias is a module that allows you to apply "aliasing semantics" to a
68             section of code, causing aliases to be made wherever Perl would normally make
69             copies instead. You can use this to improve efficiency and readability, when
70             compared to using references.
71              
72             The exact details of aliasing semantics are below under L.
73              
74             Perl 5.22 added some support for aliasing to the Perl core. It has a
75             different syntax, and a different set of operations, from that supplied by
76             this module; see L. The core's aliasing
77             facilities are implemented more robustly than this module and are better
78             supported. If you can rely on having a sufficiently recent Perl version,
79             you should prefer to use the core facility rather than use this module.
80             If you are already using this module and are now using a sufficiently
81             recent Perl, you should attempt to migrate to the core facility.
82              
83             =head1 SYNTAX
84              
85             =head2 alias I | alias I
86              
87             Exported by default.
88              
89             Enables aliasing semantics within the expression or block. Returns an alias
90             to the expression, or the block's return value.
91              
92             C is context-transparent, meaning that whichever context it is placed in
93             (list, scalar, void), the expression/block is evaluated in the same context.
94              
95             =head2 copy I | copy I
96              
97             Restores normal (copying) semantics within the expression or block, and
98             makes a copy of the result value (unless in void context).
99              
100             Like C, C is context-transparent.
101              
102             =head2 deref I
103              
104             Accepts a list of references to scalars, arrays, or hashes. Applies the
105             applicable dereferencing operator to each. This means that:
106              
107             deref $scalarref, $arrayref, $hashref
108              
109             behaves like:
110              
111             $$scalarref, @$arrayref, %$hashref
112              
113             Where an array or hash reference is given, the returned list does not
114             include the array or hash as an lvalue; the array/hash is expanded and
115             the list includes its elements. Scalars, including the elements of an
116             array/hash, I treated as lvalues, and can be enreferenced using
117             the C<\> operator or aliased to using the C operator. This is
118             slightly different from what you'd get using the built-in dereference
119             operators: C<@$arrayref> references the array as an lvalue, so C<\>
120             or C can operate on the array itself rather than just its elements.
121              
122             =head1 EXAMPLES
123              
124             A common usage of aliasing is to make an abbreviation for an expression, to
125             avoid having to repeat that (possibly verbose or ugly) expression over and
126             over:
127            
128             alias my $fi = $self->{FrobnitzIndex};
129             $fi = $fi > 0 ? $fi - $adj : $fi + $adj;
130              
131             sub rc4 {
132             alias my ($i, $j, $S) = @_;
133             my $a = $S->[($i += 1) &= 255];
134             my $b = $S->[($j += $S->[$i]) &= 255];
135             $S->[(($S->[$j] = $a) + ($S->[$i] = $b)) & 255]
136             }
137              
138             In the second example, the rc4 function updates its first two arguments (two
139             state values) in addition to returning a value.
140              
141             Aliasing can also be used to avoid copying big strings. This example would
142             work fine without C but would be much slower when passed a big string:
143              
144             sub middlesection ($) {
145             alias my $s = shift;
146             substr $s, length($s)/4, length($s)/2
147             }
148              
149             You can also apply aliasing semantics to an entire block. Here this is used to
150             swap two arrays in O(1) time:
151              
152             alias {
153             my @temp = @x;
154             @x = @y;
155             @y = @temp;
156             };
157              
158             The C function is typically used to temporarily reinstate normal
159             semantics, but can also be used to explicitly copy a value when perl would
160             normally not do so:
161              
162             my $ref = \copy $x;
163              
164             =head1 DETAILS
165              
166             This section describes exactly what the aliasing semantics are of operations.
167             Anything not listed below has unaltered behaviour.
168              
169             =over 4
170              
171             =item scalar assignment to variable or element.
172              
173             Makes the left-side of the assignment an alias to the right-side expression,
174             which can be anything.
175              
176             alias my $lexvar = $foo;
177             alias $pkgvar = $foo;
178             alias $array[$i] = $foo;
179             alias $hash{$k} = $foo;
180              
181             An attempt to do alias-assignment to an element of a tied (or "magical") array
182             or hash will result in a "Can't put alias into tied array/hash" error.
183              
184             =item scalar assignment to dereference
185              
186             If $ref is a reference or undef, this simply does C<$ref = \$foo>. Otherwise,
187             the indicated package variable (via glob or symbolic reference) is made an
188             alias to the right-side expression.
189              
190             alias $$ref = $foo;
191              
192             =item scalar assignment to glob
193              
194             Works mostly the same as normal glob-assignment, however it does not set the
195             import-flag. (If you don't know what this means, you probably don't care)
196              
197             alias *glob = $reference;
198              
199             =item scalar assignment to anything else
200              
201             Not supported.
202              
203             alias substr(...) = $foo; # ERROR!
204             alias lvalsub() = $foo; # ERROR!
205              
206             =item conditional scalar assignment
207              
208             Here C<$var> (and C<$var2>) are aliased to C<$foo> if the applicable condition
209             is satisfied. C<$bool> and C<$foo> can be any expression. C<$var> and
210             C<$var2> can be anything that is valid on the left-side of an alias-assignment.
211              
212             alias $bool ? $var : $var2 = $foo;
213             alias $var &&= $foo;
214             alias $var ||= $foo;
215             alias $var //= $foo; # (perl 5.9.x or later)
216              
217             =item whole aggregate assignment from whole aggregate
218              
219             This occurs where the expressions on both sides of the assignment operator
220             are purely complete arrays or hashes.
221             The entire aggregate is aliased, not merely the contents.
222             This means for example that C<\@lexarray == \@foo>.
223              
224             alias my @lexarray = @foo;
225             alias my %lexhash = %foo;
226             alias @pkgarray = @foo;
227             alias %pkghash = %foo;
228              
229             Making the left-side a dereference is also supported:
230              
231             alias @$ref = @foo;
232             alias %$ref = %foo;
233              
234             and analogously to assignment to scalar dereference, these will change C<$ref>
235             to reference the aggregate, if C<$ref> was undef or already a reference. If
236             C<$ref> is a string or glob, the corresponding package variable is aliased.
237              
238             Anything more complex than a whole-aggregate expression on either side,
239             even just enclosing the aggregate expression in parentheses, will prevent
240             the assignment qualifying for this category. It will instead go into
241             one of the following two categories. Parenthesisation is the recommended
242             way to avoid whole-aggregate aliasing where it is unwanted. If you want
243             to merely replace the contents of the left-side aggregate with aliases
244             to the contents of the right-side aggregate, parenthesise the left side.
245              
246             =item whole aggregate assignment from list
247              
248             If the left-side expression is purely a complete array or hash,
249             and the right-side expression is not purely a matching aggregate, then a new
250             aggregate is implicitly constructed. This means:
251              
252             alias my @lexfoo = (@foo);
253             alias my @array = ($x, $y, $z);
254             alias my %hash = (x => $x, y => $y);
255              
256             is translated to:
257              
258             alias my @lexfoo = @{ [@foo] };
259             alias my @array = @{ [$x, $y, $z] };
260             alias my %hash = %{ {x => $x, y => $y} };
261              
262             If you want to merely replace the contents of the aggregate with aliases to the
263             contents of another aggregate, rather than create a new aggregate, you can
264             force list-assignment by parenthesizing the left side, see below.
265              
266             =item list assignment
267              
268             List assignment is any assignment where the left-side is an array-slice,
269             hash-slice, or list in parentheses. This behaves essentially like many scalar
270             assignments in parallel.
271              
272             alias my (@array) = ($x, $y, $z);
273             alias my (%hash) = (x => $x, y => $y);
274             alias my ($x, $y, @rest) = @_;
275             alias @x[0, 1] = @x[1, 0];
276              
277             Any scalars that appear on the left side must be valid targets for scalar
278             assignment. When an array or hash appears on the left side, normally as the
279             last item, its contents are replaced by the list of all remaining right-side
280             elements. C can also appear on the left side to skip one corresponding
281             item in the right-side list.
282              
283             Beware when putting a parenthesised list on the left side. Just like Perl
284             parses C as C<(print(1+2))*10>, it would parse C
285             = ($y, $x)> as C<(alias($x, $y)) = ($y, $x)> which does not do any aliasing,
286             and results in the "Useless use of alias" warning, if warnings are enabled.
287              
288             To circumvent this issue, you can either one of the following:
289              
290             alias +($x, $y) = ($y, $x);
291             alias { ($x, $y) = ($y, $x) };
292              
293             =item Anonymous aggregate constructors
294              
295             Return a reference to a new anonymous array or hash, populated with aliases.
296             This means that for example C<\$hashref-E{x} == \$x>.
297              
298             my $arrayref = alias [$x, $y, $z];
299             my $hashref = alias {x => $x, y => $y};
300              
301             Note that this also works:
302              
303             alias my $arrayref = [$x, $y, $z];
304             alias my $hashref = {x => $x, y => $y};
305              
306             but this makes the lhs an alias to the temporary, and therefore read-only,
307             reference made by C<[]> or C<{}>. Therefore later attempts to assign to
308             C<$arrayref> or C<$hashref> results in an error. The anonymous aggregate that
309             is referenced behaves the same in both cases obviously.
310              
311             =item Array insertions
312              
313             These work as usual, except the inserted elements are aliases.
314              
315             alias push @array, $foo;
316             alias unshift @array, $foo;
317             alias splice @array, 1, 2, $foo;
318              
319             An attempt to do any of these on tied (or "magical") array will result in a
320             "Can't push/unshift/splice alias onto tied array" error.
321              
322             =item Returning an alias
323              
324             Returns aliases from the current C or C. Normally this only
325             happens for lvalue subs, but C can be used in any sub.
326             Lvalue subs only work for scalar return values, but C
327             can handle a list of return values.
328              
329             A sub call will very often copy the return value(s) immediately after
330             they have been returned. C can't prevent that. To pass
331             an alias through a sub return and into something else, the call site
332             must process the return value using an aliasing operation, or at least a
333             non-copying one. For example, ordinary assignment with the sub call on
334             the right hand side will copy, but if the call site is in the scope of an
335             C pragma then the assignment will instead alias the return value.
336              
337             When alias-returning a list of values from a subroutine, each individual
338             value in the list is aliased. The list as a whole is not aliasable;
339             it is not an array. At the call site, a list of aliases can be captured
340             into separate variables or into an array, by an aliasing list assignment.
341              
342             =item Subroutines and evaluations
343              
344             Placing a subroutine or C inside C causes it to be compiled
345             with aliasing semantics entirely. Additionally, the return from such a sub or
346             eval, whether explicit using C or implicitly the last statement, will
347             be an alias rather than a copy.
348              
349             alias { sub foo { $x } };
350              
351             my $subref = alias sub { $x };
352            
353             my $xref1 = \foo;
354             my $xref2 = \alias eval '$x';
355             my $xref3 = \$subref->();
356              
357             Explicitly returning an alias can also be done using C inside any
358             subroutine or evaluation.
359              
360             sub foo { alias return $x; }
361             my $xref = \foo;
362              
363             =item Localization
364              
365             Use of local inside C usually behaves the same as local does in general,
366             however there is a difference if the variable is tied: in this case, Perl
367             doesn't localise the variable at all but instead preserves the tie by saving a
368             copy of the current value, and restoring this value at end of scope.
369              
370             alias local $_ = $string;
371              
372             The aliasing semantics of C avoids copying by always localizing the
373             variable itself, regardless of whether it is tied.
374              
375             =back
376              
377             =head1 IMPLEMENTATION
378              
379             This module does B use a source filter, and is therefore safe to use
380             within eval STRING. Instead, Data::Alias hooks into the Perl parser, and
381             replaces operations within the scope of C by aliasing variants.
382              
383             For those familiar with perl's internals: it triggers on a ck_rv2cv which
384             resolves to the imported C sub, and does a parser hack to allow the
385             C syntax. When the ck_entersub is triggered that corresponds to
386             it, the op is marked to be found later. The actual work is done in a peep-hook,
387             which processes the marked entersub
388             and its children, replacing the pp_addrs with aliasing replacements. The peep
389             hook will also take care of any subs defined within the lexical (but not
390             dynamical) scope between the ck_rv2cv and the ck_entersub.
391              
392             =head1 KNOWN ISSUES
393              
394             =over 4
395              
396             =item Lexical variables
397              
398             When aliasing existing lexical variables, the effect is limited in scope to the
399             current subroutine and any closures create after the aliasing is done, even if
400             the variable itself has wider scope. While partial fixes are possible, it
401             cannot be fixed in any reliable or consistent way, and therefore I'm keeping
402             the current behaviour.
403              
404             When aliasing a lexical that was declared outside the current subroutine, a
405             compile-time warning is generated "Aliasing of outer lexical variable has
406             limited scope" (warnings category "closure").
407              
408             =back
409              
410             =head1 ACKNOWLEDGEMENTS
411              
412             Specials thanks go to Elizabeth Mattijsen, Juerd Waalboer, and other members of
413             the Amsterdam Perl Mongers, for their valuable feedback.
414              
415             =head1 AUTHOR
416              
417             Matthijs van Duin developed the module originally,
418             and maintained it until 2007. Andrew Main (Zefram)
419             updated it to work with Perl versions 5.11.0 and later.
420              
421             =head1 LICENSE
422              
423             Copyright (C) 2003-2007 Matthijs van Duin.
424             Copyright (C) 2010, 2011, 2013, 2015, 2017
425             Andrew Main (Zefram) .
426             All rights reserved.
427             This program is free software; you can redistribute it and/or modify
428             it under the same terms as Perl itself.
429              
430             =cut
431              
432             __PACKAGE__