加上一句「;及;在Perl中逗号插值数组的最后一个元素之前

加上一句「;及;在Perl中逗号插值数组的最后一个元素之前,perl,Perl,我想创建一个子例程,在元素中添加逗号,并在最后一个元素之前添加“and”,例如,使“12345”变为“1、2、3、4和5”。我知道如何添加逗号,但问题是我得到的结果是“1、2、3、4和5”,我不知道如何去掉最后一个逗号 sub commas { my @with_commas; foreach (@_) { push (@with_commas, ($_, ", ")); #up to here it's fine } splice @with_commas, -

我想创建一个子例程,在元素中添加逗号,并在最后一个元素之前添加“and”,例如,使“12345”变为“1、2、3、4和5”。我知道如何添加逗号,但问题是我得到的结果是“1、2、3、4和5”,我不知道如何去掉最后一个逗号

sub commas {
  my @with_commas;
  foreach (@_) {
    push (@with_commas, ($_, ", ")); #up to here it's fine
    }
    splice @with_commas, -2, 1, ("and ", $_[-1]);
    @with_commas;
  }
正如您可能知道的,我正在尝试删除新数组中的最后一个元素(@带有逗号),因为它附加了逗号,并添加了旧数组中的最后一个元素(@,从主程序传递到子程序,没有添加逗号)

当我运行这个程序时,结果是,例如,“1,2,3,4和5”-结尾是逗号。那个逗号是从哪里来的?只有带逗号的@才应该得到逗号


感谢您的帮助。

添加逗号,然后添加“and”:

#!/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";
因此,当您有两个以上的元素时,可以这样做:

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;
您可以使用并修改最后一个元素以包含

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

这也处理只有一个元素的列表,与大多数其他答案不同。

正是本着TIMTOWTDI的精神(尽管坦率地说,@perreal的答案在可读性方面更好):


这有点类似于Alan的答案(更复杂/复杂),但与之相比的好处是,如果您需要在最后一个元素之外的任何其他元素中添加“and”,它将起作用;Alan's仅在您知道确切的偏移量(例如最后一个元素)时才起作用。

有一个CPAN模块用于此。我自己使用它,并推荐它胜过滚动您自己的解决方案。用法语法非常简单:

conjunction(@list);
小提示

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

或者,如果有人能提出一种完全不同的更好的方法,我洗耳恭听。我不知道如何加入
join
,所以这很有启发性!谢谢所有回复的人。哇,谢谢!我还在学习,但还有很多,欢迎你。我自己也错过了很多次,我想我找到它只是因为有人指给我看。我认为如果你不去寻找“连接词”,那就很难找到了。
sub commas {
    my $last_index = $#_;
    my @with_commas = map { (($_==$last_index) ? "and " : "") . $_[$_] }
                          0 .. $last_index;
    print join("," @with_commas)
}
conjunction(@list);
for( 1 .. 10 ) {
     print ;
     $_ == 10 ? print '' : ($_ != 9 ? print ', ' : print ' and ');
}