Perl: Loops (for and while) - by Eun Bae Kim (07/26/2018)
 

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
  
use strict;

# for loop: 0 through 9
print "--------------------------------------------\n";
for (my $i=0; $i<10;$i++) {
	print $i."\t";
}
print "\n";


# for loop: 1 through 9
for (my $i=1; $i<=9;$i++) {
	print $i."\t";
}
print "\n";

# Sum of 1 through 10
print "--------------------------------------------\n";
my $iSum = 0;
for (my $i=1; $i<=10;$i++) {
	$iSum = $iSum + $i;
	print $i."\t".$iSum."\n";
}



# Double for loop - the rules of multiplication (±¸±¸´Ü)
print "--------------------------------------------\n";
for (my $i=2; $i<=9;$i++) {
	for (my $j=1; $j<=9;$j++) {
		print $i." X ".$j." = ".($i*$j)."\n";
	}
	print "------------\n";
}




# foreach loop
my @aMembers = ("EBKim", "JBPark", "HCNoh", "GDJin");       # Creating a variable
my %hScore_by_Student   = ();       # Creating a variable
$hScore_by_Student{"EBKim"}  = 50;
$hScore_by_Student{"HCNoh"}  = 70;
$hScore_by_Student{"JBPark"} = 40;
$hScore_by_Student{"GDJin"}  = 60;

print "--------------------------------------------\n";
foreach my $sCurElement (@aMembers) {
	print $sCurElement."\t";
}
print "\n";

print "--------------------------------------------\n";
foreach my $sCurKeys (keys %hScore_by_Student) {
	print $sCurKeys."\t".$hScore_by_Student{$sCurKeys}."\n";
}





# while loop
my $iCond1 = 1;
my $iCond2 = 1;
print "--------------------------------------------\n";
while ($iCond1 == 1) { # repeat again and again if iCond1 is 1
	print $iCond1."\t"."iCond1 is 1\n";
	$iCond1++;
}
print $iCond1."\t"."Stopped here!"."\n";

print "--------------------------------------------\n";
until ($iCond2 == 4) {  # repeat if iCond2 is not 4
	print $iCond2."\t"."iCond2 is not 4\n";
	$iCond2++;
}
print $iCond2."\t"."Stopped here!"."\n";





# Controlling while loop
my $iNum  = 0;
print "--------------------------------------------\n";
while (1) {       # Always the condition is TRUE(1). 0 is FALSE.
	$iNum++;

	if ($iNum >= 5001) {
		last;
	}

	if ($iNum % 1000 == 0) { # % Modulus for remainder
		print "Current iNum = ".$iNum."\n";
	}
}



# For more information, refer to the following link
# https://www.tutorialspoint.com/perl