LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   perl "my" problem (https://www.linuxquestions.org/questions/linux-newbie-8/perl-my-problem-835678/)

PoleStar 10-01-2010 01:32 PM

perl "my" problem
 
Good day,


If I declare some thing in a loop like

Code:

use strict;

if($val == 1){

my $temp = $val;

}

....

some more loops


print "$temp";


It tells me

"Global symbol "$temp" requires explicit package name at..."



Any ideas ?

AlucardZero 10-01-2010 01:44 PM

Since you declared it within a block, it does not exist outside of that block. Declare/initialize it before the if statement.

http://en.wikipedia.org/wiki/Scope_(programming)

PoleStar 10-01-2010 01:59 PM

So can I make macro othe top of program, #define style?


Problem is this loop is going to run through many entries.
And I want to keep certain variables, even when the loop ends.

TB0ne 10-01-2010 02:01 PM

Quote:

Originally Posted by PoleStar (Post 4115061)
So can I make macro othe top of program, #define style?

Problem is this loop is going to run through many entries.
And I want to keep certain variables, even when the loop ends.

Then don't use a "my" on it.

Using "my" means that the particular chunk doesn't exist outside that loop. Leaving it off will define it globally, so other loops can use it.

PoleStar 10-01-2010 02:04 PM

So you suggest I don't use "strict" ?


Because when I take of my from the loop/block
It bring back same error on that line.

AlucardZero 10-01-2010 02:23 PM

No, I suggest you do this.

Code:

use strict;

my $temp = 0;

if($val == 1){

$temp = $val;

}

....

some more loops


print "$temp";

That way $temp is still in scope when you print it.

PoleStar 10-01-2010 02:38 PM

oh

Its so much like C.

Thanks alot.

ghostdog74 10-01-2010 09:04 PM

Quote:

Originally Posted by PoleStar (Post 4115090)
Its so much like C.

Fun reading


All times are GMT -5. The time now is 08:49 PM.