Basic for loops

October 25th, 2012 by Erin Scott

One of the first things anyone taking the leap into programming is going to learn is the ever present, ever useful for loop. One of the reasons a for loop is so useful is that it implements exactly what computers do best and what people do worst, tedious repetitive tasks. Imagine having to grab a specific piece of data from 100 different vcards or manually update 1000 rows in someones SQL database. Not fun, and that’s where for loops come in, giving you the ability to program a specific set of tasks and then let your computer crunch away at the numbers while you relax and sip your favourite coffee product. It’s like the old saying goes, laziness is the mother of efficiency and a good for loop will help you accomplish both of those.

The basic for loop consists of a set of values which are either numbers or a set of strings, a temp variable that is what you use to access the data you’re iterating through, and a criteria that has to be fulfilled so that the loop knows when to stop. It’ll probably make more sense when there is a live example so look below to get a better understanding.

Here is a basic for loop written in Perl that iterates through a given set of IP’s to see which ones are responding.

#!/usr/bin/perl
# Declare current subnet
$subnet = “192.168.0.”;
# Initialize temp variable ($var), stop after number 10 ($var <= 11) and for each loop add one ($var++)
for (my $var = 1; $var <= 11; $var++) {
    # Send one ping per IP
    `ping -c 1 $subnet$var`;
    # And finally print which hosts are up
    print “$subnet$var is up\n” if ($? == 0);
}

 

Comments are closed.