Hi luupski,
Another way to do this is with the join function, which lets you avoid appending the final comma in the first place.
Read the data from your file, split it on whitespace, join each datum with commas, and surround the entire record with parentheses:
foreach my $line (<$infh>) {
if ($line =~ /$re_data/) {
# Split on whitespace, surround with parens, join with commas
push @data, "(" . join(",", split(/\s+/, $line)) . ")";
}
}
and finally, join the records with a comma followed by a newline. The last record won't get a comma (nor newline):
# Simply 'join' all data; last record contains neither comma nor newli
+ne.
my $data = join(",\n", @data);
Here's an entire working example:
#!/usr/bin/perl
use strict;
use warnings;
use feature qw( say );
use IO::File;
##################
## User-defined ##
##################
my $input = 'in.txt'; # Input file
my $output = 'out.txt'; # Output file
my $re_data = qr/^[0-9]+/; # Detect lines containing records
##################
## Main program ##
##################
# Read the input
my $infh = IO::File->new($input) or die "Can't read '$input' ($!)";
my @data = ( );
foreach my $line (<$infh>) {
if ($line =~ /$re_data/) {
# Split on whitespace, surround with parens, join with commas
push @data, "(" . join(",", split(/\s+/, $line)) . ")";
}
}
close($infh);
# Simply 'join' all data; last record contains neither comma nor newli
+ne.
my $data = join(",\n", @data);
# Create the output
my $text = qq{
SELECT CUSTOMERID, ORDERID, CUSTOMERNAME, CUSTOMERLOCATION
FROM DB.CUSTOMER_DATA
WHERE (CUSTOMERID, ORDERID, CUSTOMERNAME, CUSTOMERLOCATION) IN (
$data
)
};
$text =~ s/\n\s+/\n/g; # Remove indentation (for "looks")
# Write the output
my $outfh = IO::File->new;
open($outfh, '>', $output) or die "Can't write '$output' ($!)";
print $outfh $text;
close($outfh);
say "Wrote '$output'";
The output for which is:
SELECT CUSTOMERID, ORDERID, CUSTOMERNAME, CUSTOMERLOCATION
FROM DB.CUSTOMER_DATA
WHERE (CUSTOMERID, ORDERID, CUSTOMERNAME, CUSTOMERLOCATION) IN (
(0001,20000001,john,CA),
(0002,30000002,neill,WI),
(0003,40000003,joe,GA),
(0004,50000004,will,IL),
(0005,60000005,mike,IN),
(0006,70000006,bill,AK)
)
say
substr+lc crypt(qw $i3 SI$),4,5
|