Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Perl Misc (http://www.velocityreviews.com/forums/f67-perl-misc.html)
-   -   FAQ 5.40 Why do I get weird spaces when I print an array of lines? (http://www.velocityreviews.com/forums/t914501-faq-5-40-why-do-i-get-weird-spaces-when-i-print-an-array-of-lines.html)

PerlFAQ Server 01-17-2011 11:00 PM

FAQ 5.40 Why do I get weird spaces when I print an array of lines?
 
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
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 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
perlfaq.pod.


All times are GMT. The time now is 04:49 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.