in reply to Proper way to initialize local variables

Both local @recArray; and my @recArray; will give you an empty array to start with, but the latter is considered better because it has lexical scope, while the former has dynamic scope. This means that, for example, in

our @foo = ( 0 ); my @bar = ( 'a' ); { local @foo = ( 1 ); my @bar = ( 'b' ); baz(); print "$foo[ 0 ] $bar[ 0 ]\n"; # may not print "1 b" } sub baz { $foo[ 0 ] = 3; $bar[ 0 ] = 'x'; } __END__ 3 b
...calling the function baz() has the effect of changing the value of $foo[ 0 ] inside the block; in contrast, the lexical variable @bar remains unaffected by what happens in baz().

By the way, the scoping behavior described above is not specific to arrays; it applies equally to hashes, scalars, and typeglobs as well.

the lowliest monk

Replies are listed 'Best First'.
Re^2: Proper way to initialize local variables
by rzward (Monk) on May 11, 2005 at 22:45 UTC
    Thank you for your explanation of local vs. my.

    I actually asked a question about this topic some time ago. Unfortunately, I don't know how to put a link in this discussion to point to it!

    It sounds like it's impossible for an array declared with local or my to start off not empty even if the array is not explicitly initialized.

    Thank you again.

    Richard