perl - Understanding Arrays of Arrays -
i'm going through documentation of perldsc in section of array of arrays , shows array of arrays looks like
@aoa = ( [ "fred", "barney" ], [ "george", "jane", "elroy" ], [ "homer", "marge", "bart" ], );
in next section on lines 1 - 4 shows how generate one
# reading file while ( <> ) { push @aoa, [ split ]; }
i want learn how create one. created file , had following contents in it.
john adam joe
rod fred james
allison frank jean
then used code example create array of arrays
#!/usr/bin/perl -w use strict; use data::dumper; @aoa; while ( <> ) { push @aoa, [ split ]; } print dumper(@aoa);
when ran code, contents of dumper is
$var1 = [ 'john', 'adam', 'joe' ]; $var2 = [ 'rod', 'fred', 'james' ]; $var3 = [ 'allison', 'frank', 'jean' ];
as can see, printed 3 arrays, thought should print array of arrays.
but when ran same code small modification
print dumper(\@aoa);
it printed.
$var1 = [ [ 'john', 'adam', 'joe' ], [ 'rod', 'fred', 'james' ], [ 'allison', 'frank', 'jean' ] ];
which array of arrays.
here understanding of \@aoa. pointer memory location of @aoa. please clarify why had use \@aoa output expected?
update
i think confusion explained in perlreftut
one of important new features in perl 5 capability manage complicated data structures multidimensional arrays , nested hashes. enable these, perl 5 introduced feature called references, , using references key managing complicated, structured data in perl.
references in perl names arrays , hashes. they're perl's private, internal names, can sure they're unambiguous. unlike "barack obama", reference refers 1 thing, , know refers to. if have reference array, can recover entire array it. if have reference hash, can recover entire hash. reference still easy, compact scalar value. can't have hash values arrays; hash values can scalars. we're stuck that. single reference can refer entire array, , references scalars, can have hash of references arrays, , it'll act lot hash of arrays, , it'll useful hash of arrays.
this due how variables passed perl subroutines.
a sub
takes list of variables, of length, arguments. if call sub array argument, array elements passed in sub.
so
my @array = (1,2,3); foo(@array);
is no different sub's perspective:
my $a = 1; $b = 2; $c = 3; foo($a,$b,$c);
if call dumper()
array, list of array elements. won't "see" array unless pass in reference.
Comments
Post a Comment