How to create a while loop in perl
How to create a while loop in perl
This post snipped is to show you how to create a while loop using perl, obviously this is possible in almost every programming language.
Scenario
You have to make some checks or print something until a certain limit or count. For eg. you want to print a count until 10.
Solution
1 2 3 4 5 6 7 8 |
my $count = 0; while ($count < 10) { print "$count \n"; # Printing the current count $count++; # Incrementing the count } print "Counting has finished\n"; |
Output result would be similar to:
1 2 3 4 5 6 7 8 9 |
0 1 2 3 4 5 6 7 Counting has finished |
Multiple while loops
You can also run multiple loops inside another loop, of course it will run slower depending on what the inner loops are doing as each main loop will need to finish the inner one. So careful with these.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
my $count = 0; my $second = 0; while ($count < 4) { while ($second < 4) { print "$second \n"; # Printing the current count $second++; # Incrementing $second } if ($second == 4 ) { $second = 0; # reinitializing the $second variable } print "Finished Second, count: $count \n"; # Printing the current count loop $count++; # Incrementing $count } print "Counting has finished\n"; |
Output of this loop will look similar to:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
0 1 2 3 Finished Second, count: 0 0 1 2 3 Finished Second, count: 1 0 1 2 3 Finished Second, count: 2 0 1 2 3 Finished Second, count: 3 Counting has finished |
That’s it with this, happy coding!