我们遍历数据库并将每一行推送到数组
while (($carriergw) = $sth->fetchrow_array) {
if ($rows >= 1) {
push(@gwlist, $carriergw);
}
else {
push(@gwlist, -1);
}
}
例如,这会产生数组(0 10)
。当我尝试加入元素时
在每个元素后添加分号:
join(';', @gwlist)
join函数添加一个前导半冒号(即;10;0
)。我们需要的只是10;0
。怎么样
获取没有任何前导或尾随分隔符的列表?
答案 0 :(得分:3)
您的数组@gwlist
的第一个元素为空字符串或undef
。你是如何申报的?我想你已经写过了
my @gwlist = undef;
如果你写
my @gwlist;
push @gwlist, 10;
push @gwlist, 0;
print join ';', @gwlist;
然后您将获得10;0
输出。您需要调查第一个元素的来源。
顺便说一句,您的while
循环最好写成
while (my ($carriergw) = $sth->fetchrow_array) {
push @gwlist, $rows > 0 ? $carriergw : -1;
}
但$rows
上的测试几乎肯定是不必要的。您没有说它的值来自何处,但如果没有从表中检索到行,则看起来您想要推送单个-1
。如果是这种情况,则永远不会输入while
循环,因此即使-1
也不会添加到数组中。
答案 1 :(得分:2)
可能有一个空元素,undef
或只是空格作为gwlist[0]
的第一个(@gwlist
)元素。要绕过它,您可以关闭第一个元素,或使用数组切片:
shift @gwlist;
join ';', @gwlist;
或者:
join ';', @gwlist[1..$#gwlist]
答案 2 :(得分:2)
my @l = (undef, 0, 10);
print join(";", @l), "\n";
给出:
;0;10
如果您使用警告,它也会说:
Use of uninitialized value $l[0] in join or string at test.pl line 5
您可以通过过滤来阻止这种情况:
print join(";", grep { defined $_ } @l), "\n";