Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PERL

perl loops

# The main loops in Perl are for, foreach, and while, though there are also
# do..while and until loops. Here's the syntax for each, with examples:
# Basic syntax of for loop:
for ( init; condition; increment ) {
    code to run;
}
# Example usage of for loop:
for (my $i = 5; $i < 10; $i += 1) {  
    print "Value of i: $i
";
}

# Basic syntax of foreach loop:
foreach var (list) {
	code to run;
}
# Example usage of foreach loop:
@list = (2, 20, 30, 40, 50);
foreach $i (@list) {
    print "Value of i: $i
";
}

# Basic syntax of while loop:
while( condition ) {
   code to run;
}
# Example usage of while loop:
my $i = 5;
while( $i < 10 ) {
   print "Value of i: $i
";
   $i += 1;
}

# Basic syntax of do..while loop:
# Similar to while loop but always executes at least once
do {
   code to run;
} while( condition );
# Example usage of do..while loop:
$i = 5;
do {
   print "Value of i: $i
";
   $i += 1;
} while( $i < 10 );

# Basic syntax of until loop:
# Sort of the opposite of a while loop, it loops over the code until the
# condition becomes true
until( condition ) {
   code to run;
}
# Example usage of until loop:
$i = 5;
until( $i > 10 ) {
   print "Value of i: $i
";
   $i += 1;
}
Source by www.tutorialspoint.com #
 
PREVIOUS NEXT
Tagged: #perl #loops
ADD COMMENT
Topic
Name
5+8 =