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?

To answer this question, we first need a sample Perl array. Let's assume that you have an array that contains the name of baseball teams, like this:

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

Perl array printing

Now, 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.

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:

cubs
reds
yankees
dodgers
Permalink

The example:

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

Should actually be:

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

Permalink

I agree that the last method you've shown is a little obtuse:
print join("\n",@teams),"\n";

But I believe there's another (but similar) method:
print join "\n",@teams;

PeterB

Permalink

peterb, that's just the same thing, without newline at the end (which should be there).
alvin, thanks for a very nice summary.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.