9

Added a & ldquo; And & rdquo; Before the last element in a comma-interpo...

 2 years ago
source link: https://www.codesd.com/item/added-a-and-before-the-last-element-in-a-comma-interpolated-array-in-perl.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Added a & ldquo; And & rdquo; Before the last element in a comma-interpolated array in Perl

advertisements

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.

Tags perl

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK