Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

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

0 views
Skip to first unread message

PerlFAQ Server

unread,
May 22, 2008, 9:03:03 AM5/22/08
to
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.39: 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
quotes:

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 contexts, Perl joins the elements
of spaces (or whatever is in $", which is a space by default):

animals are: camel llama alpaca vicuna

This is different than print 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 becoming 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 it in double
quotes. You can send

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
perlfaq.pod.

0 new messages