【发布时间】:2019-07-30 23:01:41
【问题描述】:
我是一名新手 perl 程序员,试图识别哪些元素在一个哈希数组中,但不在另一个哈希数组中。我正在尝试搜索“新”数组,识别“旧”数组中不存在的 id、标题和创建的元素。
我相信我可以使用一组基本的 for() 循环,但我想更有效地做到这一点。这只是在尝试使用 grep() 并失败后才出现的。
这些数组是从数据库中构建的:
use DBI;
use strict;
use Data::Dumper;
use Array::Utils qw(:all);
sub db_connect_new();
sub db_disconnect_new($);
sub db_connect_old();
sub db_disconnect_old($);
my $dbh_old = db_connect_old();
my $dbh_new = db_connect_new();
# get complete list of articles on each host first (Joomla! system)
my $sql_old = "select id,title,created from mos_content;";
my $sql_new = "select id,title,created from xugc_content;";
my $sth_old = $dbh_old->prepare($sql_old);
my $sth_new = $dbh_new->prepare($sql_new);
$sth_old->execute();
$sth_new->execute();
my $ref_old;
my $ref_new;
while ($ref_old = $sth_old->fetchrow_hashref()) {
push @rv_old, $ref_old;
}
while ($ref_new = $sth_new->fetchrow_hashref()) {
push @rv_new, $ref_new;
}
my @seen = ();
my @notseen = ();
foreach my $i (@rv_old) {
my $id = $i->{id};
my $title = $i->{title};
my $created = $i->{created};
my $seen = 0;
foreach my $j (@rv_new) {
if ($i->{id} == $j->{id}) {
push @seen, $i;
$seen = 1;
}
}
if ($seen == 0) {
print "$i->{id},$i->{title},$i->{state},$i->{catid},$i->{created}\n";
push @notseen, $i;
}
}
使用 Dumper(@rv_old) 打印数组时,数组如下所示:
$VAR1 = {
'title' => 'Legal Notice',
'created' => '2004-10-07 00:17:45',
'id' => 14
};
$VAR2 = {
'created' => '2004-11-15 16:04:06',
'id' => 86096,
'title' => 'IRC'
};
$VAR3 = {
'id' => 16,
'created' => '2004-10-07 16:15:29',
'title' => 'About'
};
我尝试通过数组引用来使用 grep(),但我认为我对数组、哈希和引用的理解不够好,无法正确执行。我失败的 grep() 尝试如下。对于如何正确执行此操作的任何想法,我将不胜感激。
我认为问题在于我不知道如何引用第二个哈希数组中的 id 字段。我见过的大多数使用 grep() 的示例只是查看整个数组,就像使用常规 grep(1) 一样。我需要遍历一个数组,检查 id 字段中的每个值与另一个数组中的 id 字段。
my $rv_old_ref = \@rv_old;
my $rv_new_ref = \@rv_new;
for my $i ( 0 .. $#rv_old) {
my $match = grep { $rv_new_ref->$_ == $rv_old_ref->$_ } @rv_new;
push @notseen, $match if !$match;
}
我还尝试了上面 grep() 的变体:
1) if (($p) = grep ($hash_ref->{id}, @rv_old)) {
2) if ($hash_ref->{id} ~~ @rv_old) {
【问题讨论】:
标签: arrays database perl mariadb