Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 619
Mike Avatar asked May 21 '10 15:05

Mike


People also ask

How to split using in Perl?

Perl | split() Function. split() is a string function in Perl which is used to split or you can say to cut a string into smaller sections or pieces. There are different criteria to split a string, like on a single character, a regular expression(pattern), a group of characters or on undefined value etc..


2 Answers

print join(',', @list), "\n";
like image 54
WhirlWind Avatar answered Oct 20 '22 18:10

WhirlWind


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.

like image 24
P Shved Avatar answered Oct 20 '22 18:10

P Shved