Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re^3: Accessing Arguments inside Subroutines via @_

by AppleFritter (Vicar)
on Mar 21, 2015 at 16:59 UTC ( [id://1120843]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Accessing Arguments inside Subroutines via @_
in thread Accessing Arguments inside Subroutines via @_

Pure Perl has neither an explicit alias operator

You can (ab)use typeglobs for this, at least for package variables. For instance:

#!/usr/bin/perl no strict; use warnings; use feature qw/say/; $a = 42; *b = *a; say $b; # 42 $b = 69; say $a; # 69

I can't think of a way of doing this with lexicals off the top of my head, though.

nor an explicit unalias operator.²

So if a scalar variable $a is an alias to $b you can't easily say $a=42 without changing $b , i.e. replacing the alias in the $a -"slot" with a literal 42.¹

I don't think this is needed. Suppose that you have variables - let's say lexicals - $a and $b, with the latter being aliased to the former. Unalias $a would mean creating a new lexical that's not related to $b anymore, so why not just declare a new lexical with the same value (my $c = $b) and use that instead? The result's the same, and it's arguably clearer, since if you look at any line in isolation there's no confusion over whether $a is (still) aliased to $b anymore.

OTOH there's something to be said in favor of explicit alias and unalias operators as well. I'd not be surprised at all if there were CPAN modules that implemented this.

Replies are listed 'Best First'.
Re^4: Accessing Arguments inside Subroutines via @_
by LanX (Saint) on Mar 21, 2015 at 17:10 UTC
    I just wanted to highlight why it makes sense that assigning to @_ doesn't write thru to the aliases.

    my and local were already mentioned in my footnote, when using typeglobs I'd strongly suggest to prefer *b = \$a; over  *b = *a;

    But these mechanisms are no big help if you want named parameters in subs cause those are lexicals, (which should be the preferred variable flavor).

    > I'd not be surprised at all if there were CPAN modules that implemented this.

    see Data::Alias or Lexical::Alias and their discussion in PBP

    Perl6 aims to handle aliasing consistently.

    Cheers Rolf
    (addicted to the Perl Programming Language and ☆☆☆☆ :)

    PS: Je suis Charlie!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (2)
As of 2024-04-16 23:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found