How to print a Perl array

Summary: How to use a Perl foreach loop to print every element in a Perl array.

To look at how to print every element in a Perl array using the foreach operator, the first thing we need is a sample array. Let's assume that you have an array that contains the name of baseball teams, like this:

@teams = ('cubs', 'reds', 'yankees', 'dodgers');

If you just want to print the array with the array members separated by blank spaces, you can just print the array like this:

@teams = ('cubs', 'reds', 'yankees', 'dodgers');
print "@teams\n";

But that's not usually the case. More often, you want each element printed on a separate line. To achieve this, you can use this code:

@teams = ('cubs', 'reds', 'yankees', 'dodgers');

foreach (@teams) {
  print "$_\n";

In many examples you'll see the variable $_. This is a special Perl variable that holds the value of the element currently being processed.

In the terrific book, Programming Perl, the authors recommend another way to print the entire contents of an array. I think it's a little more difficult to understand, but that's just *my* opinion - and the Perl motto is "There's More Than One Way To Do It" - so here it is:

@teams = ('cubs', 'reds', 'yankees', 'dodgers');
print join("\n",@ARGV),"\n";

If you run one of these last two examples, you'll get this result: