http://www.perlmonks.org?node_id=586121

jdporter has asked for the wisdom of the Perl Monks concerning the following question: (references)

For example,

my $x; my $y; make_alias( $x, $y ); $x = 5; print $y; # prints 5

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How to force one variable to be an alias to another?
by jdporter (Paladin) on Nov 26, 2006 at 21:33 UTC

    One way is to use the Lexical::Alias module:

    use Lexical::Alias; my( $this, $that ); alias $that, $this; # $this is now an alias for $that.
    Here, $this is made to be an alias of $that. Whatever $this contained prior to the alias call (e.g. the 2 in the above example) is released, much the same as if $this had simply gone out of scope. (That is, its ref count is decremented.) Similarly, the reference count of whatever $that contains is incremented by this operation.

    You can also create aliases for array and hash variables this way:

    alias @x, @y; alias %x, %y;

    Note that this technique specifically only works for lexical variables; it does not work for package variables or other globals, such as array elements and hash values.

    Another, similar approach is to use Tie::Alias. It has the advantage that it's pure Perl, but it's both slower and (currently) only works for scalars.

    use Tie::Alias; my( $this, $that ); tie $this, 'Tie::Alias', \$that; # $this is now an alias for $that.

Re: How to force one variable to be an alias to another?
by vrk (Chaplain) on Mar 09, 2017 at 11:05 UTC

    Perl 5.22 introduced the refalias feature. The simplest solution to the example is

    use v5.22; use warnings; use feature 'refalias'; # Silence warnings if desired: no warnings 'experimental::refaliasing'; my ($x, $y); \$x = \$y; # alias here $x = 5; say $y; # prints 5
Re: How to force one variable to be an alias to another?
by LanX (Saint) on Nov 21, 2008 at 12:27 UTC
    Data::Alias is now preferred over Lexical::Alias, as it works with globals (package variables, array elements, hash values, etc.) as well as lexicals.
Re: How to force one variable to be an alias to another?
by ww (Archbishop) on Mar 11, 2017 at 14:58 UTC
Re: How to force one variable to be an alias to another?
by merlyn (Sage) on Nov 26, 2006 at 17:19 UTC
    There are many CPAN modules that have the word Alias in the name, with varying support, features, and documentation. Without further clarification, you'll have to sort them out yourself.

    Originally posted as a Categorized Answer.