我试图使用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。或者绳子..。
谢谢!
发布于 2014-11-25 14:33:55
#!/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();发布于 2014-11-25 16:08:26
让我们来看看你的代码。加了些评论。
#!/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();https://stackoverflow.com/questions/27129010
复制相似问题