CJ7
CJ7

Reputation: 23275

Why does printing a list output last item in list?

print "Val: " . ('a','b','c');

The output is:

c

Why?

It doesn't matter how you do it. It could be:

sub test {
    return ('a','b','c');
}
print "Val: " . test();

Upvotes: 0

Views: 67

Answers (2)

Dave Sherohman
Dave Sherohman

Reputation: 46187

The concatenation operator (.) takes two scalars as operands, so your list gets evaluated in scalar context. As explained in roderick young's answer, a list returns its final value when evaluated in scalar context, due to the way the comma operator works.

If you want to print all of the items in the list, you can either use , instead of . in the print statement or (probably better) use join to convert the list to a scalar before concatenating:

$ perl -E 'say "Val: ", ("a", "b", "c")'
Val: abc
~$ perl -E 'say "Val: " . join("-", ("a", "b", "c"))'
Val: a-b-c

Upvotes: 3

roderick young
roderick young

Reputation: 304

http://blogs.perl.org/users/steven_haryanto/2012/09/the-comma-operator.html

explains the comma operator. To quote them,

"...It is just the binary comma operator in action. In the scalar context, the comma operator (quoting the perlop manpage verbatim) "evaluates its left argument, throws that value away, then evaluates its right argument and returns that value. This is just like C's comma operator." So the end result is the rightmost argument..."

Upvotes: 5

Related Questions