I want to create a subroutine that adds commas to elements and adds an “and” before the last element, e.g., so that “12345” becomes “1, 2, 3, 4, and 5”. I know how to add the commas, but the problem is the result I get is “1, 2, 3, 4, and 5,” and I don’t know how to get rid of the last comma.
sub commas {
my @with_commas;
foreach (@_) {
push (@with_commas, ($_, ", ")); #up to here it's fine
}
splice @with_commas, -2, 1, ("and ", $_[-1]);
@with_commas;
}
As you can probably tell, I’m trying to delete the last element in the new array (@with_commas), since it has the comma appended, and add in the last element in the old array (@_, passed to the sub routine from the main program, with no added comma).
When I run this, the result is, e.g., “1, 2, 3, 4, and 5,” — with the comma at the end. Where is that comma coming from? Only @with_commas was supposed to get the commas.
Any help is appreciated.
This also handles lists with only one element, unlike most of the other answers.