我想创建一个子程序,在元素中添加逗号,并在最后一个元素之前添加"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;
}
正如你可能知道的,我正试图删除新数组中的最后一个元素(@with_commas),因为它附加了逗号,并添加旧数组中的第二个元素(@c_,从主程序传递到子例程,没有添加逗号)。
当我运行这个程序时,结果是,例如,"1、2、3、4和5"——末尾有逗号。这个逗号是从哪里来的?只有@with_commas应该得到逗号。
感谢您的帮助。
sub format_list {
return "" if !@_;
my $last = pop(@_);
return $last if !@_;
return join(', ', @_) . " and " . $last;
}
print format_list(@list), "n";
与大多数其他答案不同,这也处理只有一个元素的列表。
您可以使用join
并修改最后一个元素以包含and
:
my @list = 1 .. 5;
$list[-1] = "and $list[-1]" if $#list;
print join ', ', @list;
有一个CPAN模块,Lingua::Conjunction。我自己使用它,并建议它超越您自己的解决方案。用法语法非常简单:
conjunction(@list);
#!/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";
添加逗号,然后添加"and":
use v5.10;
my $string = join ', ', 1 .. 5;
substr
$string,
rindex( $string, ', ' ) + 2,
0,
'and '
;
say $string;
因此,当你有两个以上的元素时,就应该这样做:
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;
正是本着TIMTOWTDI的精神(尽管坦率地说,@perreal的答案在可读性方面更好):
sub commas {
my $last_index = $#_;
my @with_commas = map { (($_==$last_index) ? "and " : "") . $_[$_] }
0 .. $last_index;
print join("," @with_commas)
}
这与Alan的答案有点相似(更复杂/更复杂),但与之相比的好处是,如果你需要在上一个元素之外的任何OTHER元素中添加"and",它都会起作用;Alan只有当你知道确切的偏移量(例如最后一个元素)时才有效。
小提示
for( 1 .. 10 ) {
print ;
$_ == 10 ? print '' : ($_ != 9 ? print ', ' : print ' and ');
}