in reply to How does my $self = (@_) actually work?
Then, as you expect, the 'age' value of your $self-referenced object becomes 17. If you did something like this:sub X { my $self = shift; $self->{age} = 17; }
You will note that $self does not change in the function, and that in both cases it is clearly a reference to a HASH.sub X { my $self = shift; print "\$self = $self\n"; $self->{age} = 17; print "\$self = $self\n"; }
In this case, $bar is not modified, though a copy of it, called $foo, is. Here's an example that uses a reference instead:sub Z { my ($foo) = @_; print "\$foo = $foo\n"; $foo = 17; print "\$foo = $foo\n"; } my $bar = 29; print "\$bar = $bar\n"; Z($bar); print "\$bar = $bar\n";
On the way into the function, the variable is prefixed with a backslash, meaning "pass by reference". Inside the function, the scalar is "used" with a second $, meaning that you are modifying the value, not the reference. This is another form of dereferencing, not unlike the "arrow operator" used by arrays and hashes.sub Z { my ($foo) = @_; print "\$foo = $foo\n"; $$foo = 17; print "\$foo = $foo\n"; } my $bar = 29; print "\$bar = $bar\n"; Z(\$bar); print "\$bar = $bar\n";
|
|---|