in reply to Two Questions on "my"

Answer 1
I would use the second variation, because it hides $foo from the rest of the code, eliminating the possibility of side-effects from having $foo still visible. The code generated by this Perl reuses your scoped $foo anyway as an optimization, so there is no penalty.

Note that my ($foo); could be more clearly represented as my $foo; - the parens are usually used in declarations to collapse several lines into one, such as:

my ($a, $b, $c);
or
my ($a, $b, $c) = (0, 1, 2);
or to capture a subroutine's arguments
my ($a, $b) = @_;

Answer 2
The declaration of $key and $value both outside and inside the loop is redundant, but I see nothing wrong with your code inside the loop, other than the fact that the loop control variable $i is not referenced in the body, so the loop could be rewritten as:

for (1 .. $a_whole_lot) { my ($key, $value) = returnsAnArray (); }
Again, the scoped variables are going to be reused.

Aside
In question 1, your code doesn't even need a $foo.

codethatUsesFoo (getValue()) for 1 .. $a_huge_value;
In general, you are using the C-style for loop, and it would be more Perlish of you to use for or foreach as shown.

Hope this helps.

Replies are listed 'Best First'.
Re: Re: Two Questions on "my"
by duff (Parson) on May 22, 2004 at 21:15 UTC
    In question 1, your code doesn't even need a $foo.
    codethatUsesFoo (getValue()) for 1 .. $a_huge_value;
    While I agree with your sentiment regarding the more perlish for loop, you have slightly changed the semantics by placing the call to getValue() within the parameter list of codethatUsesFoo(). The orginal code had getValue in scalar context, while yours has it in list context. This may or may not make a difference in reality, but it's always important to be aware of such subtlties IMHO.