FAQ 5.40 Why do I get weird spaces when I print an array of lines?


PerlFAQ Server

This is an excerpt from the latest version perlfaq5.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .


5.40: Why do I get weird spaces when I print an array of lines?

(contributed by brian d foy)

If you are seeing spaces between the elements of your array when you
print the array, you are probably interpolating the array in double

my @animals = qw(camel llama alpaca vicuna);
print "animals are: @animals\n";

It's the double quotes, not the "print", doing this. Whenever you
interpolate an array in a double quote context, Perl joins the elements
with spaces (or whatever is in $", which is a space by default):

animals are: camel llama alpaca vicuna

This is different than printing the array without the interpolation:

my @animals = qw(camel llama alpaca vicuna);
print "animals are: ", @animals, "\n";

Now the output doesn't have the spaces between the elements because the
elements of @animals simply become part of the list to "print":

animals are: camelllamaalpacavicuna

You might notice this when each of the elements of @array end with a
newline. You expect to print one element per line, but notice that every
line after the first is indented:

this is a line
this is another line
this is the third line

That extra space comes from the interpolation of the array. If you don't
want to put anything between your array elements, don't use the array in
double quotes. You can send it to print without them:

print @lines;


The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question