Perl array printing: How do I print the entire contents of an array with Perl?

Perl array FAQ: How do I print the entire contents of an array in Perl?

A sample array

To answer this question we first need a sample Perl array, such as an array that contains the name of baseball teams:

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

Solution: Perl array printing

Now, if you just want to print the array with the array members separated by blank spaces, you can 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.

Perl array printing from Programming Perl

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",@teams),"\n";

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