Perl: breaking a foreach loop when the last element of an array is encountered

Perl noob is here. I have a small script (see below) that I use to create a MySQL INSERT statement.

use strict;

my @records = qw/Record1 Record2 Record3/;

my $insert = "
INSERT INTO table
VALUES
 ";

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

print "$insert\n";

Current output

INSERT INTO table
VALUES
 ('Record1'),
 ('Record2'),
 ('Record3'),

I need to know how to split the last element of an array @recordsand add ;instead,

Desired output

INSERT INTO table
VALUES
 ('Record1'),
 ('Record2'),
 ('Record3');
+3
source share
2 answers

You can do this with mapand 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

The method is better than just putting the material in quotation marks because it handles the bad stuff for you. It’s not very different from the loop , but will make sure that the commas are between the elements, and not the last.quote $dbhmapforeachjoin

+6
source

sql , sql. perl /, :

my @records = qw/Record1 Record2 Record3/;
$sth = $dbh->prepare("INSERT INTO table VALUES ?");

foreach my $record (@records) {
      $sth->execute($record);   
}

http://bobby-tables.com/perl.html

+1

All Articles