in reply to hard versus soft reference to ARRAY's

ok : i should have used strict en warnings
use strict; use warnings; my $dwarfs = [ qw(Doc Grumpy Happy Sleepy Sneezy Dopey Bashful) ]; print "@{$dwarfs}\n"; my @removed=(); my $removed=""; @removed = splice @{$dwarfs},3 ,2; #$removed = [ @removed ]; #1. please notice : this makes a copy first + of @removed . # changes to @{$removed} will NOT affect @removed # OUTPUT : Sleepy Sneezy $removed = \@removed ; #2. please notice : this is a hard reference +. # changes to @{$removed} will affect @removed. # OUTPUT : Sleepy # let's examine the above : Just uncomment one of the above beginning + with : $removed pop @{$removed} ; print "@removed\n";

Replies are listed 'Best First'.
Re^2: hard versus soft reference to ARRAY's
by AnomalousMonk (Archbishop) on Jan 25, 2016 at 23:40 UTC

    This is, for the most part, just a picky restatement of some points I was trying to make above. But references are tricky, so I want to make these points clearly.

    The statement
        $removed = [ @removed ];
    creates a hard reference to an anonymous array initialized by a shallow copy from the  @removed array. The statement
        $removed = \@removed;
    also creates a hard reference, but to the named  @removed array. The nature of both these references is the same, but their referents, the things they reference, are different. Hence, the difference in behavior when using these two references.

    #$removed =  [ @removed ]; #1. please notice : this makes a copy first of @removed . # changes to @{$removed} will NOT affect @removed

    It is not true that changes to  $removed will not affect the referent. Because the anonymous array is initialized by a shallow copy, accesses by reference to lower levels of the referent, if such exist, can change the referent. E.g.:

    c:\@Work\Perl\monks>perl -wMstrict -le "use Data::Dump qw(dd); ;; my @ra = ([ qw(fee fie foe) ], [ qw(original stuff) ], [ qw(uno dos t +res) ]); dd \@ra; ;; my $hardref = [ @ra ]; dd $hardref; print '-------------'; ;; $hardref->[1] = 'ZOT!'; $hardref->[0][2] = 'KAPOW!'; $hardref->[2][1] = 'WHAM!'; dd $hardref; dd \@ra; " [ ["fee", "fie", "foe"], ["original", "stuff"], ["uno", "dos", "tres"], ] [ ["fee", "fie", "foe"], ["original", "stuff"], ["uno", "dos", "tres"], ] ------------- [["fee", "fie", "KAPOW!"], "ZOT!", ["uno", "WHAM!", "tres"]] [ ["fee", "fie", "KAPOW!"], ["original", "stuff"], ["uno", "WHAM!", "tres"], ]
    Note that a change to the "top" level of the  $hardref reference ('ZOT!') does not change the original content of the  @ra array, but a more indirect or "lower" level access ('KAPOW!' 'WHAM!') does. As I say, tricky.


    Give a man a fish:  <%-{-{-{-<