Mar 23, 2013

For Vs Foreach in Perl


Today we discuss about the difference between For & Foreach with simple examples:

FOR Syntax:
Syntax :for (initialization; test; re-initialization) BLOCK


#!/usr/bin/perl
use strict;
use warnings;

print "\nStart For Loop"; 

for ($count = 1; $count <= 5; $count++) {
  print "\nEach Element : " . $count;
}
print "\nEnd For Loop"; 


O/P:
Start For Loop
Each Element : 1
Each Element : 2
Each Element : 3
Each Element : 4
Each Element : 5
End For Loop


Foreach
The foreach keyword is actually a synonym for the "for" keyword, so we can use "foreach" (more readability or brevity)


#!/usr/bin/perl
use strict;
use warnings;

@array = ("Mother Teresa", "Abraham Lincoln", "Nelson Mandela");
foreach my $each (@array) {
  print "\nEach Element : " . $each;
}


O/P:
Each Element : Mother Teresa
Each Element : Abraham Lincoln
Each Element : Nelson Mandela


No comments:

Post a Comment