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.
sub format_list {
return "" if !@_;
my $last = pop(@_);
return $last if !@_;
return join(', ', @_) . " and " . $last;
}
print format_list(@list), "\n";
This also handles lists with only one element, unlike most of the other answers.
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