in reply to Re^2: Accessing Arguments inside Subroutines via @_
in thread Accessing Arguments inside Subroutines via @_
Hello LanX,
I think what is really troubling you is the ambiguity between setting a symbol's slot and assigning to a symbol in Perl.
I’m not sure if I understand the distinction you’re making here, but my current understanding of a Perl alias is that it’s in some ways analogous to a smart pointer. That is, it has its own identity as a scalar value (of type “alias”), but under certain conditions it behaves “transparently” as the entity it aliases, like a dereferenced pointer. To explain what I mean: I was experimenting with various permutations of the following code:
use strict; use warnings; use Data::Dump; my $x = 1; my $y = 2; print "x = $x, y = $y\n"; swap($x, $y); print "x = $x, y = $y\n"; sub swap # External SWAP? { # -------------- # @_ = reverse @_; # NO # ( $_[0], $_[1] ) = ( $_[1], $_[0] ); # YES # @_[0, 1] = @_[1, 0]; # YES - slice # splice @_, 0, 2, reverse @_; # NO - splice # splice @_, 0, 2, ( $_[1], $_[0] ); # NO - splice # @_[$#_ + 1] = 12; # Preserves aliasing # push @_, 'x'; # Preserves aliasing unshift @_, 'y'; # Preserves aliasing, but +changes indices $_[1] = 55; dd \@_; }
and the output shows that following unshift @_ the element $_[1] is now an alias for the first argument. So, when explaining how @_ functions in a subroutine, I would no longer say “$_[0] is an alias for the first argument,” but rather “$_[0] is initialised to a (scalar value which is an) alias for the first argument.”
And the difference in behaviour between, e.g., @_ = reverse @_ and ( $_[0], $_[1] ) = ( $_[1], $_[0] ), comes down to whether the aliases act “transparently” or ”opaquely.” When elements of @_ are accessed individually — whether singly or as part of an array slice — they behave “transparently,” but when the array @_ is assigned-to — via = or splice — its alias values are accessed “opaquely,” meaning their referents remain unaffected.
Well, that’s my current understanding, and it may be just a convoluted way of repeating your explanation in different words. Anyway, I think I now understand what’s going on a little better than I did before. :-)
Update: Fixed typo.
Thanks for the help,
Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^4: Accessing Arguments inside Subroutines via @_
by LanX (Saint) on Mar 22, 2015 at 12:06 UTC |