green69
green69

Reputation: 1720

cannot acces variable inside while loop (in perl)

A very easy question on variables scope. I have a variable defined in the main code that I use inside a while loop.

my $my_variable;
while(<FILE>) {
   ...using $my_variable
}
if ($my_variable) -> FAILS

When I exit the loop and use the variable I get an error:

Use of uninitialized value $my_variable

Even if I enclose the variable in a naked block I follow with the error.

{
    my $my_variable;
    while(<FILE>) {
       ...using $my_variable
    }
    if ($my_variable) -> FAILS
}

Any suggestion?

Upvotes: 0

Views: 2301

Answers (3)

Axeman
Axeman

Reputation: 29854

  • Are you using $my_variable in the loop or did you redefine it as my $my_variable somewhere in the loop. You'd be surprised how easily a my slips in to variable assignment.

    I even have a frequent tick in my code where I write something like

     my $hash{ $key } = ... some elaborate assignment;
    
  • Also, if should not complain about an uninitialized variable. undef => Boolean false.

  • I wouldn't worry about initializing all my variables -- but its crucial that you learn a mindset about how to use undefs. And always, always USUW (use strict; use warnings) so that variables aren't uninitialized when you don't expect them to be.

Upvotes: 1

Toto
Toto

Reputation: 91385

In the examples given, you didn't initialize $my_variable so it is undefined after the while loop.

You can do my $my_variable = ''; just before the loop.

Upvotes: 0

musiKk
musiKk

Reputation: 15189

Do you ever assign to $my_variable? All you show is a declaration (the my) and a usage (the if) but never an assignment.

Upvotes: 1

Related Questions