Perl for loop - How to do something for each element in an array

Perl for loop FAQ: What is the Perl for loop syntax? (Also written as, "How do I perform some type of operation on every element in a Perl array?)

Perl has a nice "for loop" syntax that lets you iterate through each element in an array, and perform some operation on each element.

Here's a simple Perl for loop example where I first create a small array, and then use the for loop to print each element in the array:

# array.pl
#
# a simple perl program to demonstrate how to iterate through
# each element in an array with a perl for loop

# create a simple array
@words = qw(anchorage talkeetna denali fairbanks);

# use the perl for loop to operate on each element in a perl array
for (@words)
{
  print "$_\n";
}

Perl for loop example - output

When you save this Perl for loop code to a file, and then run it through the Perl interpreter, like this:

prompt> perl array.pl 

this program produces the following output:

anchorage
talkeetna
denali
fairbanks

In most cases you'll probably have to do a little more work on each element in your Perl array, but this example shows the basic Perl for loop syntax to make this happen.

 

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.