Consider the below code for example:
@array=(1..10);
print @array;
print "@array";
The output is as follows:
12345678910
1 2 3 4 5 6 7 8 9 10
This is a question about string conversion and interpolation. In perl, "
is treated differently to '
, in that perl is asked to interpolate any variables in the string.
That's why:
my $str = "fish";
print "This is a $str\n";
Works. (With single quotes, it wouldn't). But for things that aren't strings, perl applies some conversion rules. Pretty basic for most cases - a numeric value gets turned into the string equivalent (in base 10). So:
my $num = 10;
print "The number is $num\n";
"just works" rather than forcing you to use printf
/sprintf
to format convert a numeric value to an appropriate representation.
So the reason you get your first result is that print
takes a list of arguments.
So print @array
is actually print 1,2,3,4,5,6,7,8,9,10;
.
That gives you the result, because you haven't specified a separator to your print
. (You can do this by setting $,
- see below)
However "@array"
is using @array
in an explicitly stringified context, and so first it unpacks the array and space separates it.
This behaviour is controlled by the special variable $"
. You can read about this in perlvar
$" = ":";
print "@array";
See also: Interpolating Arrays into Strings
You can also 'tell' print to separate the values it's got, using $,
. By default, it's not set (e.g. is undef - see also perlvar) - so you get your first behaviour.
But you could:
$, = ",";
print @array;