sravs
sravs

Reputation: 61

Sleep function not working inside for loop using Perl Script

My code is:

#!/usr/local/bin/perl 
use Time::Piece;
use Time::HiRes;
use strict;
use warnings 'all';
my $i = 1;
my $starttime = localtime->strftime('%Y%m%d%H%M');
open my  $file, '>', 'order.properties' or die $!;
for ($i = 1; $i <= 10; $i++){   
  print $file "Start_time_$i = $starttime\n";
  sleep (120);
}
close $file;

In the above code I am creating an order.properties file and writing a variable called Starttime and assigning date and time in a format of YYYYMMDDHH24MM and iterating the variable for 10 time with sleep time 2 mins, but sleep is not working and after adding sleep function to the Script, it's just creating a file not writing anything into it.

For each iteration of for loop I need 2 mins of sleep like:

 Start_time_1 = 201812141350
 Start_time_2 = 201812141352

The output should be like above.

Upvotes: 0

Views: 828

Answers (1)

Dave Cross
Dave Cross

Reputation: 69284

You set $starttime outside of the loop and never change it. Therefore it always has the same value. If you want it to change in the loop, then you need to change it in the loop.

for ($i = 1; $i <= 10; $i++){  
  my $starttime = localtime->strftime('%Y%m%d%H%M'); 
  print $file "Start_time_$i = $starttime\n";
  sleep (120);
}

Of course, at that point, you have to wonder if there's any good reason to have the variable at all.

for ($i = 1; $i <= 10; $i++){  
  print $file "Start_time_$i = ", localtime->strftime('%Y%m%d%H%M'), "\n";
  sleep (120);
}

And, please make your maintenance programmer's life easier by using a foreach loop there.

foreach my $i (1 .. 10) {  
  print $file "Start_time_$i = ", localtime->strftime('%Y%m%d%H%M'), "\n";
  sleep (120);
}

Upvotes: 1

Related Questions