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