Showing posts with label for. Show all posts
Showing posts with label for. Show all posts

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


For Loop in Perl


FOR Loop Syntax in Perl:

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



Dec 5, 2012

Unix For Loop


#]mkdir for_test_dir1

#]mkdir for_test_dir2

#]mkdir for_test_dir3

#]cat for_test_dir1/for_test.txt
content 1
content 1
content 1

#]cat for_test_dir2/for_test.txt
content 2
content 2
content 2

#]cat for_test_dir3/for_test.txt
content 3
content 3
content 3
...
...

#] ls
for_test_dir1 for_test_dir2 for_test_dir3 for_test_dir4 for_test_dir5
......
......


#]foreach var (`ls`)
foreach? ls -ltr $var/for_test*
foreach? end

O/P:
It will list all the for_test files present in for_test_dir's