Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: while going through perldsc tutorial...

by naikonta (Curate)
on Oct 17, 2007 at 08:31 UTC ( #645400=note: print w/ replies, xml ) Need Help??


in reply to while going through perldsc tutorial...

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!


Comment on Re: while going through perldsc tutorial...
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://645400]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (9)
As of 2014-11-21 12:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (111 votes), past polls