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

Referncing a local array outside

by richard_hawkes (Initiate)
on Dec 16, 2003 at 13:27 UTC ( [id://315052]=perlquestion: print w/replies, xml ) Need Help??

richard_hawkes has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I'd like to create an associative array containing references to regular arrays (lists). The regular arrays are being created in a loop. Here is a basic example of what I'm doing:

#!/usr/bin/perl

# Create some arrays of random numbers...
foreach $NAME ('Fred', 'Barney', 'Wilma', 'Peggy')
{
        local (@ARRAY) = ();

        for ($i = 0; $i < 5; $i++)
        {
                push (@ARRAY, int(rand(30)));
        }

        # And now store the reference in an associative array...
        $ALINK{$NAME} = \@ARRAY;
}

# Here's how I might print it out...
foreach $KEY (keys (%ALINK))
{
        @ARRAY = @{ $ALINK{$KEY} };
        foreach $ELEMENT (@ARRAY)
        {
                print $KEY . " " . $ELEMENT . "\n";
        }
}

My question is: Am I risking it using the 'local' statement because it will be picked up later by garbage collection? If I am, then what's the best way to create new lists and keep a reference to them?

Thanks your holynesses!
Richard

Replies are listed 'Best First'.
Re: Referncing a local array outside
by broquaint (Abbot) on Dec 16, 2003 at 13:44 UTC
    You really ought to be using the my declaration there to create a lexically scoped variable, as opposed to local which creates a new, dynamically scoped instance of the given package variable (or hash element or array item). So in your case you're creating a dynamically scoped new instance of the package variable @ARRAY for each loop iteration, whereas you ideally want a lexically scoped variable bound to the current scope (which would the body of the loop in this case). For more information on variables and scoping within perl see. Lexical scoping like a fox.
    HTH

    _________
    broquaint

Re: Referncing a local array outside
by edoc (Chaplain) on Dec 16, 2003 at 13:49 UTC

    you could ditch the temporary variable altogether..

    #!/usr/bin/perl use strict; my %alink; # Create some arrays of random numbers... foreach my $name ('Fred', 'Barney', 'Wilma', 'Peggy'){ for (my $i = 0; $i < 5; $i++){ push( @{$alink{$name}}, int(rand(30)) ); } } foreach my $key (keys %alink){ foreach my $element ( @{$alink{$key}} ){ print $key,' ',$element,"\n"; } }

    (also added 'use strict;' and then 'my' declarations as required.)

    cheers,

    J

Re: Referncing a local array outside
by Abigail-II (Bishop) on Dec 16, 2003 at 13:38 UTC
    There's no need at all to use 'local' here. Just use 'my @ARRAY;' instead, and then you should be safe.

    Abigail

Re: Referncing a local array outside
by Zaxo (Archbishop) on Dec 16, 2003 at 19:25 UTC

    Just for fun, let's construct it in one statement with $_ the only temporary variable,

    @ALink{'Fred', 'Barney', 'Wilma', 'Peggy'} = map { [map {int rand 30} 0..4] } 0..3;
    That's called a hash slice.

    After Compline,
    Zaxo

Re: Referncing a local array outside
by welchavw (Pilgrim) on Dec 16, 2003 at 15:37 UTC

    Richard,

    The suggestions that you use my, not local, are completely correct and should be followed. However, in the interest of completely answering your questions, I wanted to add that it is my understanding that "early" garbage collection of your localized vars would not happen. Localized variables are gc'd like other variables - if outstanding references exist, such variables are not eligible for gc.

    BTW, I am writing this without reference to any particular documentation, just my experience of dynamic scoping. If my understanding here is incorrect, I will be shocked and would much appreciate learning the error of my ways from those that know better (part of the reason I post this).

    ,welchavw

Re: Referncing a local array outside
by xenchu (Friar) on Dec 16, 2003 at 15:09 UTC

    This question is mere curiosity and may be ignored without prejudice. Why are you associating names(I assume users) with a random number? Are the numbers to be used as keys?

    Thanks,

    xenchu


    The Needs of the World and my Talents run parallel to infinity.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://315052]
Approved by barrd
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (3)
As of 2024-04-18 22:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found