How to print every element in a Perl array

Summary: A Perl for loop (foreach loop) example, showing how to loop over each element in a Perl array.

Many times you'll need to print all the elements of a Perl array, or perhaps the elements of the array that match some filtering criteria. I thought I'd share several examples of how to print the elements of a Perl array here.

Initial setup

In each of the methods shown below, assume that we have an array named @pizzas that has been defined like this:

@pizzas = qw(cheese pepperoni veggie );

A very simple method

A very simple and flexible way to print all the elements in a Perl array is to just loop through the array using the foreach operator, like this:

foreach $pizza (@pizzas) {
  print "$pizza\n";
}

That will result in this output:

cheese
pepperoni
veggie

Of course you can format that output however you'd like.

Printing an array inside quotes

You can also print all the elements of an array inside a pair of double quotes, like this:

print "@pizzas\n";

This results in the following output:

cheese pepperoni veggie

If you want all of your array elements printed on one line, separated by spaces, this is a very valid approach.

Add new comment

Anonymous format

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