Is there a simple explanation for this?
References be tricky, so I don't know how "simple" you will find this, but however...
In this first example, the anonymous reference address created in main and assigned to $data in that scope is passed to a separate variable in the scope of clear_it(), and that separate variable is assigned another anonymous reference address created therein. Notice how the the reference addresses change from point A to point B, yet are the same at points X, A and Y. After a new reference address is assigned to $data within clear_it(), whatever is done to the referenced contents (the referent) of $data inside of clear_it() can have no effect on the referent of the separate $data variable in main.c:\@Work\Perl\monks>perl -wMstrict -le "use Data::Dump qw(pp); ;; sub clear_it { my($data) = @_; print 'in clear_it(): A: ref address: ', $data; $data = []; print 'in clear_it(): B: ref address: ', $data; } ;; my $data = ['a','b']; print 'in main: X: ref address: ', $data; ;; clear_it($data); print 'in main: Y: ref address: ', $data; print 'in main: Z: ref content: ', pp $data; " in main: X: ref address: ARRAY(0x15c6f3c) in clear_it(): A: ref address: ARRAY(0x15c6f3c) in clear_it(): B: ref address: ARRAY(0x15c7074) in main: Y: ref address: ARRAY(0x15c6f3c) in main: Z: ref content: ["a", "b"]
In this example, the reference address of an anonymous array in main is again passed to clear_it(), but this time an operation is performed by reference on the referent of the original reference, specifically, assigning it the empty list. Notice that the reference addresses at points X, A, B and Y are all the same.c:\@Work\Perl\monks>perl -wMstrict -le "use Data::Dump qw(pp); ;; sub clear_it { my($data) = @_; print 'in clear_it(): A: ref address: ', $data; @$data = (); print 'in clear_it(): B: ref address: ', $data; } ;; my $data = ['a','b']; print 'in main: X: ref address: ', $data; ;; clear_it($data); print 'in main: Y: ref address: ', $data; print 'in main: Z: ref content: ', pp $data; " in main: X: ref address: ARRAY(0x1846f3c) in clear_it(): A: ref address: ARRAY(0x1846f3c) in clear_it(): B: ref address: ARRAY(0x1846f3c) in main: Y: ref address: ARRAY(0x1846f3c) in main: Z: ref content: []
This seems like a perl idiosyncrasy.
This is essentially the way references work in any language.
Give a man a fish: <%-{-{-{-<
In reply to Re: Pass array, then clear
by AnomalousMonk
in thread Pass array, then clear
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |