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

Hello,

I have a question about the following code, which is in a Perl CGI script that runs on web servers:

sub anySub
{
:
local (@recArray) ;
while (defined ($_ = <$fileHandle>))
{
push (@recArray, $_) ;
}
:
}

Is it possible for recArray to start off not empty? If so, what's the best way to make sure recArray starts off empty? How about local (@recArray) = ();?

This is an older script, so maybe using my instead of local would be better also, as in my (@recArray) = ();?

Thank you in advance for your help.

Richard

  • Comment on Proper way to initialize local variables

Replies are listed 'Best First'.
Re: Proper way to initialize local variables
by tlm (Prior) on May 11, 2005 at 22:03 UTC

    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

      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

Re: Proper way to initialize local variables
by borisz (Canon) on May 11, 2005 at 22:09 UTC
    Your array is empty. local @recarray; is enough. Maybe your sub is better done this way:
    sub any { my @recArray; local $_; ... while ( defined ($_ = <$fh> ) ) { push @recArray, $_; ... } }
    but that is just a guess.
    Boris
Re: Proper way to initialize local variables
by Zaxo (Archbishop) on May 12, 2005 at 21:34 UTC

    You can initialize in a declaration by assignment:     my @recArray = <$fileHandle>; or     local @recArray = <$fileHandle>; In array context, the diamond operator returns the entire content of the file, from the current position to the end, as a list of lines. You probably want lexical my instead of local here.

    After Compline,
    Zaxo