Printing arrays

J

juliadream

Can anyone tell my why

print @array

produces output different from

print "@array"


The second one embeds spaces between the items; the first one does not.
What is the rationale behind this?

Example:

push @temparray, "hello", "again", "today";

print @temparray; # Output: helloagaintoday

print "@temparray"; # Output: hello again today
 
J

Jürgen Exner

juliadream said:
Can anyone tell my why

print @array

produces output different from

print "@array"


The second one embeds spaces between the items; the first one does
not. What is the rationale behind this?

You are slightly mistaken.

The first example doesn't print an array, it prints a list. And print()
prints lists as a direct succession of their elements.

In the second example print() prints just a single scalar, which happens to
be a string.
And this string was created by interpolating an array inside of double
quotes which is defined as inserting the value of $" between the elements.

jue
 
M

Martin Gregory

juliadream said:
Can anyone tell my why

print @array

produces output different from

print "@array"


The second one embeds spaces between the items; the first one does not.
What is the rationale behind this?

Example:

push @temparray, "hello", "again", "today";

print @temparray; # Output: helloagaintoday

print "@temparray"; # Output: hello again today


print @array

is using @array in a list context.

It is therefore the same as saying

print $array[0], $array[1], ...

And when you ask print to print a list of things like that, it separates
them with whatever is in the Output Field Separator, which is called
$, (which is the same as $OUTPUT_FIELD_SEPARATOR). This defaults to null.

On the other hand,

print "@array"

is just asking print to print one thing: a string. Not a list of things to print.

The string has been created by expanding the array into the string.

This follows the rules for expanding arrays into strings, which are that
the array elements will be separated in the string by whatever is
in $" (which is the same as $LIST_SEPARATOR). This defaults to a space.

You can read about these variables in man perlvar. You could change
either of them in your code to force

print @array

and

print "@array"

to give you the same thing.


Dream that dream.

Martin.
 

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

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top