Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: How to force one variable to be an alias to another?

by jdporter (Paladin)
on Nov 26, 2006 at 21:33 UTC ( [id://586160]=note: print w/replies, xml ) Need Help??


in reply to How to force one variable to be an alias to another?

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://586160]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (1)
As of 2024-07-25 16:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.