my @a = (1,2,3,4,5);
print @a; #output: 12345
print \"\\n\";
print \"@a\"; #output: 1 2 3 4 5
Printing an array by putting its name with
Even better question: Why doesn't it print something like array{0x1232ef}. Print is suppose to print a string output and @a
isn't a scalar.
Heck, even better: This is a scalar context, so why not print 5
which is the number of elements in the array. This is how:
print scalar @a;
would print.
Instead, the print
command is taking some liberties to try to do what you intended and not what you said you want.
Let's take a look at this little program:
@a = qw(a b c d e);
print "@a"; #prints "a b c d e"
print "\n";
print @a; #prints "abcde"
print "\n";
print @a . "\n"; #prints "5"
print scalar @a; #prints "5"
Notice that print @a
prints abcde
, but if I add a \n
on the end, it then prints @a
in a scalar context.
Take a look at the Perldoc on print (try the command perldoc -f print
. On most systems, the entire Perl documentation is available via perldoc
)
* print LIST
* print
Prints a string or a list of strings. Returns true if successful[...]
Ah! If given a list, it'll print a list of strings.
The current value of $, (if any) is printed between each LIST item. The current value of $\ (if any) is printed after the entire LIST has been printed. Because print takes a LIST, anything in the LIST is evaluated in list context, including any subroutines whose return lists you pass to print.
Let's try a new program:
@a = qw(a b c d e);
$, = "--";
print "@a"; #prints "a b c d e"
print "\n";
print @a; #prints "a--b--c--d--e"
print "\n";
print @a . "\n"; #prints "5"
print scalar @a; #prints "5"
Hmmm... The $,
added the double dashes between the list elements, but it didn't affect the @a
in quotes. And, if $,
is mentioned in the perldoc
, why is everyone prattling about $"
?
Let's take a look at perldoc perlvar
* $LIST_SEPARATOR
* $"
When an array or an array slice is interpolated into a double-quoted string or a
similar context such as /.../ , its elements are separated by this value. Default
is a space. For example, this:
print "The array is: @array\n";
is equivalent to this:
print "The array is: " . join($", @array) . "\n";
Mnemonic: works in double-quoted context.
So, that explains everything!
The default of $"
is a single space, and the default of $,
is null. That's why we got what we got!
One more program...
@a = qw(a b c d e);
$, = "--";
$" = "++";
print "@a"; #prints "a++b++c++d++e"
print "\n";
print @a; #prints "a--b--c--d--e"
print "\n";
print @a . "\n"; #prints "5"
print scalar @a; #prints "5"