开发者

How can I output a list as comma-separated values in Perl?

Let's say I have a list of elements

开发者_如何学Python
@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?


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


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.


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.


join(',', @list);


Join the list with a comma.

@list=(1,2,3);
$output = join(",",@list);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜