Perl:遇到最后一个数组元素时断开foreach循环

use*_*741 3 mysql arrays perl

Perl noob在这里.我有一个小脚本(见下文),我用它来构建一个MySQL INSERT语句.

use strict;

my @records = qw/Record1 Record2 Record3/;

my $insert = "
INSERT INTO table
VALUES
 ";

foreach my $record (@records) {
        $insert .= "('" . $record . "'),\n ";
}

print "$insert\n";
Run Code Online (Sandbox Code Playgroud)

电流输出

INSERT INTO table
VALUES
 ('Record1'),
 ('Record2'),
 ('Record3'),
Run Code Online (Sandbox Code Playgroud)

我需要知道如何打破@records数组的最后一个元素并附加一个;而不是,

期望的输出

INSERT INTO table
VALUES
 ('Record1'),
 ('Record2'),
 ('Record3');
Run Code Online (Sandbox Code Playgroud)

sim*_*que 7

你可以用map和做join.

my @records = qw/Record1 Record2 Record3/;

my $insert = "
INSERT INTO table
VALUES
 ";

$insert .= join ',', map { '(' . $dbh->quote($_) . ')' } @records;
$insert .= ';'; # this line is not needed
Run Code Online (Sandbox Code Playgroud)

quote方法$dbh不仅仅是把东西到引号,因为它处理不好的东西对你更好.该map不是从一个非常不同的foreach环路,并join会照顾把逗号中的元素之间的,而不是最后一个.