Home: Perl Programming Help: Beginner:
Syntax query initialising variables



ogit2
Novice

Aug 16, 2017, 5:58 AM


Views: 2497
Syntax query initialising variables

What would the appropriate syntax be in the code below in reference to declaring a variable. $ref will never be used outside the loop and needs to be reset every iteration of a loop. Do I initialise outside the loop, reinitialise every time within the loop or is there a different way to do it.


Code
#Version 1 
for (my $i=0; $i <= 10; $i++)
{
my $ref = $i;
}

#Version 2
my $ref = -1;
for (my $i=0; $i <= 10; $i++)
{
$ref = $i;
}



FishMonger
Veteran / Moderator

Aug 16, 2017, 7:37 AM


Views: 2494
Re: [ogit2] Syntax query initialising variables

If $ref is only needed inside the loop and needs to be reset for each iteration, then it should be declared inside the loop. If it's not going to be reset, then it should be declared outside of the loop.

Since, in your example, $ref is just a copy of $i, do you really need that second var?

On another note, using the C style for loop is messy. It would be cleaner to use the perl style for loop.


Code
for my $i ( 0..10 ) { 
my $ref = $i;
}



ogit2
Novice

Aug 16, 2017, 7:41 AM


Views: 2492
Re: [ogit2] Syntax query initialising variables

Thank you, plus the Perl style loop definitely looks much cleaner to use. I will remember that.