簡體   English   中英

DBI :: fetchall_arrayref的Perl數組取消引用問題

[英]Perl Array Dereference Problem with DBI::fetchall_arrayref

我是Perl新手,在解引用數組時遇到問題,該數組是DBI模塊中fetchall_arrayref的結果:

my $sql = "SELECT DISTINCT home_room FROM $classlist";
my $sth = $dbh->prepare($sql);
$sth->execute;
my $teachers = $sth->fetchall_arrayref;
foreach my $teacher (@{$teachers}) {
    print $teacher;
}

運行此命令將打印引用而不是數組中的值。

但是,當我運行時:

my $arrref = [1,2,4,5];
foreach (@{$arrref}) {
print "$_\n";
}

我得到數組的值。

我究竟做錯了什么? 謝謝您的幫助!

傑夫

文檔

fetchall_arrayref方法可用於從准備和執行的語句句柄中獲取所有要返回的數據。 它返回對數組的引用,該數組每行包含一個引用

因此,在您的示例中, $teacher是ARRAY引用。 因此,您將需要遍歷此數組引用

foreach my $teacher (@{$teachers}) {
    foreach my $titem (@$teacher) {
        print $titem;
    }
}

如果您只想提取教師列,則可以使用:

my @teachers = @{$dbh->selectcol_arrayref($sql)};

fetchall_arrayref獲取查詢的所有結果,因此您實際上要返回的是對數組數組的引用。 返回的每一行將是各列的arrayref。 由於查詢只有一列,因此您可以說:

my $teachers = $sth->fetchall_arrayref;
foreach my $teacher (@{$teachers}) {
    print $teacher->[0];
}

得到你想要的。

查看更多:

Perl中的數組數組

您有對行數組的引用。 每行都是對字段數組的引用。

foreach my $teacher_row (@$teachers) {
    my ($home_room) = @$teacher_row;
    print $home_room;
}

您會看到Data :: Dumper的區別。

use Data::Dumper;
print(Dumper($teachers));
print(Dumper($arrref));

$sth->fetchall_arrayref返回對數組的引用,該數組每行包含一個引用!
這里看看DBI文檔。

根據DBI的fetchall_arrayref()文檔:

fetchall_arrayref方法可用於從准備和執行的語句句柄中獲取所有要返回的數據。 它返回對數組的引用,該數組每行包含一個引用。

您是一級間接訪問:

my $sql = "SELECT DISTINCT home_room FROM $classlist";
my $sth = $dbh->prepare($sql);
$sth->execute;
my $teachers = $sth->fetchall_arrayref;
foreach my $teacher (@{$teachers}) {
    local $" = ', ';
    print "@{$teacher}\n";
}

有時,數據結構可能難以可視化。 發生這種情況時,我求助於Data::Dumper以便可以插入如下代碼:

print Dumper $teacher;

我發現有時通過轉儲數據結構,我可以在創建用於操縱該結構的代碼時獲得一個即時映射用作參考點。 最近,我不時地使用Dumper來理清頭緒,經歷了一個結構的真實噩夢。

您可以使用map取消引用返回的結構:

@teachers = map { @$_->[0] } @$teachers;

現在您有了一個簡單的教師隊伍。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM