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

I want to create a routine that adds commas to elements and adds "and" to the last element, for example, so that "12345" becomes "1, 2, 3, 4, and 5". I know how to add commas, but the problem is that I get "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 fine } splice @with_commas, -2, 1, ("and ", $_[-1]); @with_commas; } 

As you can probably tell, I'm trying to delete the last element in a new array (@with_commas), since it has an added comma and adds the last element to the old array (@_ passed to the subprogram from the main program, without adding a comma).

When I run this, the result is, for example, "1, 2, 3, 4 and 5", with a comma at the end. Where does this comma come from? Only @with_commas was supposed to get commas.

Any help is appreciated.

+4
source share
7 answers
 sub format_list { return "" if !@ _; my $last = pop(@_); return $last if !@ _; return join(', ', @_) . " and " . $last; } print format_list(@list), "\n"; 

It also processes lists with only one item, unlike most other answers.

+7
source

You can use join and modify the last element to include and :

 my @list = 1 .. 5; $list[-1] = "and $list[-1]" if $#list; print join ', ', @list; 
+3
source

There is a CPAN module for this, Lingua :: Conjunction . I use it myself, and recommend it overturn my own solution. The usage syntax is very simple:

 conjunction(@list); 
+3
source
 #!/usr/bin/perl use warnings; use strict; sub commas { return "" if @_ == 0; return $_[0] if @_ == 1; my $last = pop @_; my $rest = join (", ", @_); return $rest.", and ".$last; } my @a = (1,2,3,4,5); print commas(@a), "\n"; 
+2
source

Add commas, then add "and":

 use v5.10; my $string = join ', ', 1 .. 5; substr $string, rindex( $string, ', ' ) + 2, 0, 'and ' ; say $string; 

So, work as if you have more than two elements:

 use v5.10; my @array = 1..5; my $string = do { if( @array == 1 ) { @array[0]; } elsif( @array == 2 ) { join ' and ', @array } elsif( @array > 2 ) { my $string = join ', ', @array; my $commas = $string =~ tr/,//; substr $string, rindex( $string, ', ' ) + 2, 0, 'and ' ; $string; } }; say $string; 
+1
source

Just in the spirit of TIMTOWTDI (although, frankly, a better answer is better than readability):

 sub commas { my $last_index = $#_; my @with_commas = map { (($_==$last_index) ? "and " : "") . $_[$_] } 0 .. $last_index; print join("," @with_commas) } 

This is somewhat similar to Alan's answer (more complicated / complicated), but an advantage compared to the fact that it will work if you need to add โ€œandโ€ to any OTHER element other than the last; Alan only works when you know the exact offset (for example, the last element)

+1
source

Little hint

 for( 1 .. 10 ) { print ; $_ == 10 ? print '' : ($_ != 9 ? print ', ' : print ' and '); } 
0
source

All Articles