Perl “for” Loops

for $i (1, 2, 3, 4, 5, 6) {
  print "$i\n";
}

@integers = (1 .. 10);
$limit = 25;
for $i (@integers, 15, 21, 23 .. $limit) {
print “$i\n”;
}

%months_days = (Jan => 31, Feb => 28, Mar => 31, Apr => 30, May => 31, Jun => 30, Jul => 31, Aug => 31, Sep => 30, Oct => 31, Nov => 30, Dec => 31)

# You could use this instead:
@months = keys %months_days;

for $i (keys %months_days) {
print “$i has %months_days{$i} days.\n”;
}

These are great for looping through an array:

foreach (@myarray) {
  print;
}

#!/usr/bin/perl

# Calculate compound interest

# Prompt user for inputs
print “Enter the starting amount: “;
$start_amount = <STDIN>;

print “Enter the starting year: “;
$year = <STDIN>;

print “How many years? “;
$duration = <STDIN>;

print “Enter the annual percentage rate: “;
$apr = <STDIN>;

# Do some nice formatting: provide column heads:
print “Year”, “\t”, “Savings Balance”, “\t”, “Interest”, “\t”, “New balance”, “\n”;

# Calculate interest for each year.
# Note where this loop begins and ends:
for $i (1 .. $duration) {
print $year, “\t”;

$year++;

print $start_amount, “\t”;

# First try this one
# $interest = ($apr / 100) * $nest_egg;

# Then try it this way
$interest = int (($apr / 100) * $start_amount * 100) / 100;
print $interest, “\t”;

$start_amount += $interest;

print $start_amount, “\n”;
} # Loop ends here.

print $year, “\t”, $start_amount, “\n”;

Resources

http://www.tizag.com/perlT/perlfor.php

See similar examples at http://www.perl.com/pub/2000/10/begperl1.html

and http://ezinearticles.com/?Create-a-Compound-Interest-Calculator-in-Perl&id=2079734.