View on
MetaCPAN is shutting down
For details read Perl NOC. After June 25th this page will redirect to
Jeff Pinyan > Lexical-Alias-0.04 > Lexical::Alias



Annotate this POD


New  2
Open  0
View/Report Bugs
Module Version: 0.04   Source  


Lexical::Alias - makes a lexical an alias for another variable


  use 5.008;
  use Lexical::Alias;

  my ($src, $dst);
  alias $src, $dst;

  my (@src, @dst);
  alias @src, @dst;

  my (%src, %dst);
  alias %src, %dst;

  # modifying $src/@src/%src
  # modifies $dst/@dst/%dst,
  # and vice-versa

  # or, if supporting Perls prior to v5.8:

  use Lexical::Alias qw( alias_r alias_s alias_a alias_h );

  my ($src, $dst);
  alias_s $src, $dst;

  my (@src, @dst);
  alias_a @src, @dst;

  my (%src, %dst);
  alias_h %src, %dst;

  alias_r \$src, \$dst;
  alias_r \@src, \@dst;
  alias_r \%src, \%dst;

  # if you prefer the alias come first...
  $Lexical::Alias::SWAP = 1;
  alias $dst, $src;  # $dst is an alias for $src


This module allows you to alias a lexical (declared with my) variable to another variable (package or lexical). You will receive a fatal error if you try aliasing a scalar to something that is not a scalar (etc.).

Parameter Swaping (new!)

Version 0.04 introduced the $Lexical::Alias::SWAP variable. When it is true, the arguments to the aliasing functions are expected in reverse order; that is, the alias comes first, and the source variable second.

(Thanks to Jenda from for requesting this.)

Exported Functions


If you alias one lexical to another lexical, then making another alias to either lexical makes all three lexicals point to the same data.

  use Lexical::Alias;

  my ($x, $y, $z);
  alias $x => $y;  # $y is an alias for $x
  alias $z => $y;  # $y (and thus $x) is an alias for $z
  $z = 10;
  print $x;        # 10

This is not a bug.

However, there does appear to be a bug in Perl 5.8.0 (which has been fixed in the development version 5.9.0); when these functions are used in a subroutine, they appear to not work fully:

  my $orig = 1;
  my $alias = 99;
  alias $orig => $alias;
  print "$orig = $alias\n";

  sub foo {
    my $orig = 1;
    my $alias = 99;
    alias $orig => $alias;
    print "foo(): $orig = $alias\n";


The expected output is "1 = 1" and "foo(): 1 = 1". It is not so. The second output is "foo(): 1 = 99". Jenda pointed this out to me, and I do not know where in the source the bug is, but it will be fixed for the next release of Perl (5.8.1).


Jeff japhy Pinyan,

Thanks to Tye McQueen for a bug fix -- this module should work from 5.005 on.


Devel::LexAlias, by Richard Clamp, from which I got (and modified) the code necessary for this module. I've wanted this feature for some time, and Richard opened the door with this module.

Variable::Alias, by Brent Dax, which is a tie() interface to aliasing all sorts of variables.

syntax highlighting: