You keep getting the same memory address of
@array. No matter how many times you iterate, since all elements of
@AoA refer to the same memory address, they all share the same value of
@array, whatever its last content. Other than making array
@array lexical, you can also assign anonymous array reference. Consider this,
#!/usr/bin/perl
use strict;
use warnings;
## first sample
print "---- 1. global \@array ----\n";
my(@aoa, @array);
for my $i (0..5) {
@array = map { "#" x $_ } (0 .. $i);
$aoa[$i] = \@array;
print "$aoa[$i]\n"; # same memory address
}
print "@$_\n" for @aoa;
## second sample
print "\n---- 2. lexical \@array ----\n";
my(@AoA);
for my $i (0..5) {
my @array = map { "#" x $_ } (0 .. $i);
$AoA[$i] = \@array;
print $AoA[$i], "\n"; # different memory address
}
print "@$_\n" for @AoA;
## third sample
print "\n---- 3. anonymous array reference ----\n";
for my $i (0..5) {
my @array =
$AoA[$i] = [ map { "#" x $_ } (0 .. $i) ];
print $AoA[$i], "\n"; # different memory address
}
print "@$_\n" for @AoA;
Output,
---- 1. global @array ----
ARRAY(0x814f618)
ARRAY(0x814f618)
ARRAY(0x814f618)
ARRAY(0x814f618)
ARRAY(0x814f618)
ARRAY(0x814f618)
# ## ### #### #####
# ## ### #### #####
# ## ### #### #####
# ## ### #### #####
# ## ### #### #####
# ## ### #### #####
---- 2. lexical @array ----
ARRAY(0x818b03c)
ARRAY(0x814ed48)
ARRAY(0x8185ab8)
ARRAY(0x8185aac)
ARRAY(0x8185a58)
ARRAY(0x8185a40)
#
# ##
# ## ###
# ## ### ####
# ## ### #### #####
---- 3. anonymous array reference ----
ARRAY(0x8183e38)
ARRAY(0x818b03c)
ARRAY(0x814ed48)
ARRAY(0x8185ab8)
ARRAY(0x8185aac)
ARRAY(0x8185a58)
#
# ##
# ## ###
# ## ### ####
# ## ### #### #####
Open source softwares? Share and enjoy. Make profit from them if you can. Yet, share and enjoy!
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.