Printing a List with Commas
Problem
You’d like to print out a list with an unknown number of elements with an “and” before the last element, and with commas between each element if there are more than two.
Solution
Use this function, which returns the formatted string:
sub commify_series {
(@_ == 0) ? '' :
(@_ == 1) ? $_[0] :
(@_ == 2) ? join(" and ", @_) :
join(", ", @_[0 .. ($#_-1)], "and $_[-1]");
}Discussion
It often looks odd to print out arrays:
@array = ("red", "yellow", "green");
print "I have ", @array, " marbles.\n";
print "I have @array marbles.\n";
I have redyellowgreen marbles.
I have red yellow green marbles.What you really want it to say is, "I
have
red,
yellow,
and
green
marbles". The function
given in the solution generates strings in that format. The word
"and" is placed between the last two list
elements. If there are more than two elements in the list, a comma is
placed between every element.
Example 4.1 gives a complete demonstration of the function, with one addition: If any element in the list already contains a comma, a semi-colon is used for the separator character instead.
Example 4-1. commify_series
#!/usr/bin/perl -w # commify_series - show proper comma insertion in list output @lists = ( [ 'just one thing' ], [ qw(Mutt Jeff) ], [ qw(Peter Paul Mary) ], [ 'To our parents', 'Mother Theresa', 'God' ], [ 'pastrami', 'ham and cheese', 'peanut butter and jelly', 'tuna' ], [ 'recycle tired, old phrases', 'ponder big, happy thoughts' ], [ 'recycle tired, old ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access