我正在尝试使用perl和DBI模块拆分mysql查询的结果。这是我的代码:
#!/usr/bin/perl -w
use DBI;
$dbh = DBI->connect('DBI:mysql:host', 'user', 'password'
) || die "Could not connect to database: $DBI::errstr";
$sql = "SELECT * FROM users;";
$sth = $dbh->prepare($sql);
$sth->execute or die "SQL Error: $DBI::errstr\n";
while (@row = $sth->fetchrow_array) {
my @value1 = split(".",@row);
my $domain = $value1[1];
print "$domain\n";
}
$dbh->disconnect();
查询结果类似于: username.domain 所以我想用“。”分割结果。仅显示“域”,但它返回错误: 在连接(。)或字符串...
中使用未初始化的值$ domain谢谢!
答案 0 :(得分:4)
让我们来看看你的代码。添加了评论。
#!/usr/bin/perl -w
# Always always, start Perl programs with "use strict" and "use warnings".
# I know you have "-w" on the shebang line, but lose that as "use warnings"
# is a more flexible improvement.
use DBI;
# If you "use strict" then you need to declare all of your variables. So
# this line should start "my $dbh = ".
$dbh = DBI->connect('DBI:mysql:host', 'user', 'password'
) || die "Could not connect to database: $DBI::errstr";
$sql = "SELECT * FROM users;";
$sth = $dbh->prepare($sql);
$sth->execute or die "SQL Error: $DBI::errstr\n";
while (@row = $sth->fetchrow_array) {
# Code is always easier to follow with good indentation.
# Several issues here.
# The first parameter to split() is a regular expression. I recommend
# always putting it in /.../ so you're not tempted to assume it's a string.
# In a regex, the dot has a special meaning. It matches any character. To
# match a literal dot, you need to escape it with a \.
# The second parameter to split() is a string to split. You can't give it
# an array (well, you can, but it will use the number of elements in the
# array which is probably not what you want!
my @value1 = split(".",@row);
my $domain = $value1[1];
print "$domain\n";
}
$dbh->disconnect();
考虑到所有这些,您的代码应该看起来更像这样:
#!/usr/bin/perl
use strict;
use warnings;
use DBI;
my $dbh = DBI->connect('DBI:mysql:host', 'user', 'password')
|| die "Could not connect to database: $DBI::errstr";
my $sql = "SELECT * FROM users;";
my $sth = $dbh->prepare($sql);
$sth->execute or die "SQL Error: $DBI::errstr\n";
while (my @row = $sth->fetchrow_array) {
# Assume $row[0] is the value to want to split
my @value1 = split(/\./, $row[0]);
my $domain = $value1[1];
print "$domain\n";
}
$dbh->disconnect();
答案 1 :(得分:-4)
#!/usr/bin/perl -w
use strict;
use warnings;
use DBI;
my $dbh = '';
my $sql = '';
my $sth = '';
my @dbRow= ();
$dbh = DBI->connect('DBI:mysql:host', 'user', 'password'
) || die "Could not connect to database: $DBI::errstr";
$sql = "SELECT * FROM users;";
$sth = $dbh->prepare($sql);
$sth->execute or die "SQL Error: $DBI::errstr\n";
while (@dbRow = $sth->fetchrow_array) {
foreach my $dbData (@dbRow)
{
print split (/\./,$dbData)->[1];
}
}
$dbh->disconnect();