gpt4 book ai didi

sql-server - 修剪数组(通过 DBI 填充)

转载 作者:行者123 更新时间:2023-12-04 01:06:16 25 4
gpt4 key购买 nike

我正在尝试使用 Perl 和 DBI 模块从 SQL Server 数据库中读取数据。我的意图是读取数据并将其打印到文本文件中(以逗号分隔)。当我这样做时,我得到这样的结果:

var1,var2,var3
40406,20 ,783
50230,78 ,680
50230,78 ,680
50230,78 ,680
50230,78 ,680

所以第二个变量数据和逗号之间有一个空格。我尝试使用下面的代码来修剪它,但它没有用。我应该如何修改我的代码以摆脱那些空格?

我的代码在这里:

#!/bin/perl
use warnings;
use strict;
use DBI;

sub trim;

my $dbs = "dbi:ODBC:DRIVER={SQL Server};SERVER={xxxx}";
my ($username, $password) = ('un', 'pwd');

my $dbh = DBI->connect($dbs, $username, $password)
or die "Can't connect to $dbs: $DBI::errstr";

my $sth = $dbh->prepare("select var1, var2, var3 from db.dbo.table")
or die "Can't prepare statement: $DBI::errstr";

$sth->execute();

my $outfile = 'temp.txt';
open OUTFILE, '>', $outfile or die "Unable to open $outfile: $!";

print OUTFILE join(",", @{$sth->{NAME}}), "\n";

while (my @re = $sth->fetchrow_array) {
print OUTFILE join(",", trim(@re)), "\n";
}

close OUTFILE;

$sth->finish();
$dbh->disconnect();

############## subroutines ##################
sub trim($) {
my $string = shift;
$string =~ s/^\s+//;
$string =~ s/\s+$//;
return $string;
}

最佳答案

您的 trim() 函数不会就地修改列表(也不会处理列表)。

因此,以真正的 TIMTOWTDI 方式,您应该修改函数以返回一个新数组:

sub trimArray {
my @arr = @_;
my @rv;
for my $val (@arr) {
$val =~ s/^\s+//;
$val =~ s/\s+$//;
push @rv, $val;
}
return @rv;
}

#and then

print OUTFILE join(",", trimArray(@re)), "\n";

或者传递一个对你的函数的引用,然后就地修改数组

sub trimInPlace {
my $arrRef = shift;
for my $val (@$arrRef) {
$val =~ s/^\s+//;
$val =~ s/\s+$//;
}
}

#and then

trimInPlace(\@re); #Note the \
print OUTFILE join(",", @re), "\n";

或使用 map

#!/bin/perl
use warnings;
use strict;
use DBI;

#... the same

while (my @re = $sth->fetchrow_array) {
print OUTFILE join(",", map { trim($_); } @re), "\n"; #Applies
#trim() to each element
}

#...

############## subroutines ##################
sub trim { #Don't use prototypes
my $string = shift;
$string =~ s/^\s+//;
$string =~ s/\s+$//;
return $string;
}

或者尝试使用 chomp,通过修改 $/,这只会删除尾随空格,仅此而已。

#!/bin/perl
use warnings;
use strict;
use DBI;

#... the same

my $old_sep = $/;
$/ = " ";
while (my @re = $sth->fetchrow_array) {
chomp(@re); #Modifies in place, returning number of changes
print OUTFILE join(",", @re), "\n";
}
$/ = $old_sep;

关于sql-server - 修剪数组(通过 DBI 填充),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1097755/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com