in reply to Re^2: Array / Hash Confusion!
in thread Array / Hash Confusion!

perlreftut and perlref are the best places to start learning about references. A reference can be thought of as a pointer to an array or hash (and a few other datatypes too, but we'll stick with arrays and hashes for now). You can have multiple references (pointers) to the same hash or array, allowing them all to see the same data. Here's a quick example:

use strict; use warnings; use feature 'say'; my @arr = (); my $ref1 = \@arr; my $ref2 = $ref1; push @arr, "Hello"; # To access an array or hash via the reference # we need to use a pointy arrow... say $ref1->[0]; # says "Hello" say $ref2->[0]; # says "Hello" again # We use an @{...} to "dereference" an array ref. # That is, to treat it like an array. push @{$ref1}, "World"; say $arr[1]; # says "World" say $ref2->[1]; # says "World" again # The dereferencing syntax can be interpolated into # strings. say "@{$ref2}"; # says "Hello World" my %h = (); # You can't store an array in a hash because hash # values are always scalars. $h{foo} = @arr; # an array in scalar context # evaluates to its length. # This stores "2" in the hash. # But you can store a reference, because a reference # is a hash. $h{bar} = $ref1; # Let's print that "Hello" string again, via the hash. say $h{bar}->[0]; # says "Hello" # Now let's take a reference to that hash. my $ref3 = \%h; # We can also print "Hello" via the hash reference say $ref3->{bar}->[0]; # says "Hello" # When you've got a big chain of pointy arrows to # navigate through references, you only need the # first one. say $ref3->{bar}[0]; # says "Hello" # Here's something a little advanced. We'll # assign a reference to a localized glob. our %h2; local *h2 = $ref3; # Now %h2 (which is a real hash, not a reference to # a hash) is an ALIAS for %h. say $h2{foo}; # says "2" delete $h2{foo}; # also deletes $h{foo}.
use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name