views:

152

answers:

5

Let's say I have a list of elements

@list=(1,2,3);
#desired output
1,2,3

and I want to print them as comma separated values. Most importantly, I do not want the last element to have a comma after it.

What is the cleanest way to do this in Perl?

+8  A: 
print join(',', @list), "\n";
WhirlWind
Don't do this. It doesn't handle any of the special cases.
brian d foy
+1  A: 
join(',', @list);
jkramer
+1  A: 

Join the list with a comma.

@list=(1,2,3);
$output = join(",",@list);
Brian Roach
+7  A: 

You have several options. The most generic is to join them with join function:

print join(',', @list), "\n";

The other way is to modify special variables, which affect print statement. For example, the effect of the above one may be achieved with

$, = ",";
$\ = "\n";
print @list;

You can also automatically join list if it undergoes double-quoted expansion:

$" = ",";
print "@list","\n";

Note that if you modify special variables like $,, $\ or $", you set them globally. To avoid it, use local keyword and enclose the operands in a block.

Pavel Shved
+3  A: 

For simple cases, join is perfect.

But if you want to produce or parse CSV files, you are better off to use Text::CSV. It will handle quoting and escaping commas and all sorts of other noxious issues for you. It is also very fast.

daotoad
Again, leading with the wrong answer! :) There are no simple cases. There are only simple test data that don't show all the real world cases.
brian d foy
Yes, @brian, there are simple cases. For example, you can easily be dealing with a spec or standard which says "The data values MAY NOT contain commas." Is `join` the right way to create CSV files in the general case? No, definitely not. But the OP asked how to print a list of values with a comma after each one except the last - nothing about the result being machine-parsable or escaping/quoting anything or any other requirements except putting commas between adjacent values - and that is *exactly* what `join` does.
Dave Sherohman
In my experience, even specs that say that end up changing, and if you are going to recommend shortcuts, you need to emphasize the pitfalls. Otherwise, people take the shortcut and hurt themselves later.
brian d foy
Using Text::CSV every time you want to print a couple of comma separated values is seriously over-engineering. On the other hand, if you're generating CSV files then it certainly is the right way to go. I stand by what I said before. Yes, specs change, programs change, sh*t-happens. Under-engineering a solution has a cost, but so does over-engineering. It's up to the practitioner to determine what approach makes sense.
daotoad