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?
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..
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With