Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an "and" before the last element in a comma-interpolated array in Perl

Tags:

perl

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.

like image 575
Marc Adler Avatar asked Dec 04 '22 02:12

Marc Adler


1 Answers

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.

like image 95
ikegami Avatar answered Jan 19 '23 04:01

ikegami