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

Hi,

In the code below involving a loop, where is the "right" place to declare variable $var - inside or outside the loop?
foreach my $elem (@somearray) { my $var = $elem == 10 ? 'found 10' : 'other number'; } my $var; foreach my $elem (@somearray) { $var = $elem == 10 ? 'found 10' : 'other number'; }
Thanks in advance :)

Replies are listed 'Best First'.
Re: Placement of "my"
by lakshmananindia (Chaplain) on Apr 02, 2009 at 13:29 UTC

    It depends on your requirement. If you don't want $var to be visible outside, then declare inside the loop.

    --Lakshmanan G.

    The great pleasure in my life is doing what people say you cannot do.


Re: Placement of "my"
by vinoth.ree (Monsignor) on Apr 02, 2009 at 13:39 UTC

    Lexical scopes of control structures are not bounded precisely by the braces that delimit their controlled blocks; control expressions are part of that scope, too. Thus in the loop the scope of $line extends from its declaration throughout the rest of the loop construct (including the continue clause), but not beyond it

    while (my $line = <>) { $line = lc $line; } continue { print $line; }

    So A my declares the listed variables to be local (lexically) to the enclosing block, file, or eval.

Re: Placement of "my"
by GrandFather (Saint) on Apr 02, 2009 at 21:55 UTC

    Outside the loop implies you want to retain the value from the last iteration of the loop.

    Inside the loop implies that the information is only applicable inside the loop.

    Program for clarity of intent rather than trying to prematurely optimize (or pessimize) your code.


    True laziness is hard work
Re: Placement of "my"
by Anonymous Monk on Apr 02, 2009 at 14:44 UTC

    Thanks everybody.

    I had this impression that if it's declared inside the loop, it's duplicative because the declaration happens iteratively over the duration of the loop.

    The scope part didn't come to mind.

      Declaration is a compile-time thing. So, it happens once. Even if you don't execute the loop.
        Ah thanks for that. It's an enlightenment to me.