CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

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

 



ogit2
Novice

Aug 16, 2017, 5:58 AM

Post #1 of 3 (1457 views)
Syntax query initialising variables Can't Post

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

Post #2 of 3 (1454 views)
Re: [ogit2] Syntax query initialising variables [In reply to] Can't Post

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

Post #3 of 3 (1452 views)
Re: [ogit2] Syntax query initialising variables [In reply to] Can't Post

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

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives