Perl - 从存储在哈希引用中的数组中获取数组值的问题

Perl - Issue getting array values from array stored in a hash reference

所以我目前正在开发一个 perl 项目,我需要将一个数组(包含要拒绝的 ID)作为哈希引用存储到另一个子程序中,我在其中访问数组使用其内容 json 我正在创建的文件。我目前希望将数组作为 ref 存储在我的主哈希中; “$self”,我在 sub 之间插入,以便访问我用来获得身份验证的令牌。对于我正在处理的网站:

#!/usr/bin/perl -I/usr/local/lib/perl
#all appropriate libaries used

#I use this to gen. my generic user agent, which is passed around.
my $hub = website->new( email=>'XXXX', password=>'XXXX'); 

# I use this to get the authorisation token, which is stored as a hash ref for accessing where needed (sub not shown)
my $token = $hub->auth(); 

#this is where I get the array of ids I want to reject
my @reject_array = $hub->approvelist(); 

# this is where the issue is happening as the array hash ref keeps just giving a total number of id's 
$hub->rejectcontacts; 


sub approvelist{
    my $self = shift;
    #$self useragent  and the token gets used in a http request to get json

    .
    #json code here to strip out the id for each contact in a for loop, which I then push into the array below  \/
    .
    .
    .
    push @idlist, $id;
    .
    .
    .
    #this is where I try to store my array as a hash 
    $self->{reject_array} = @idlist; 

    ref in $self 

    return @idlist;
}

sub rejectcontacts{
    #I do the same trick to try getting the useragent obj, the auth. token AND now the array
    my $self = shift; 
    .
    #code used for the HTTP request here...
    .
    .

    my $content = encode_json({
        reason=>"Prospect title",
        itemIds=>[@{$self->{reject_array}}], #this is where the problem is
    });

问题是,当我尝试从散列引用访问数组时,我似乎只能获得数组中元素数量的标量,而不是数组中的每个实际内容。

我已经检查过数组已定义并且哈希引用本身也已定义,但是当我尝试访问上面我的 "rejectcontacts" 子中的数组时,我得到的只是 id 的数量其中 - 68(68 数字被放入我试图编写的 json 文件中,然后显然不起作用)。

如有任何帮助,我们将不胜感激 - 我无法在其他地方找到解决方案。

这里:

$self->{reject_array} = @idlist;

您正在将数组分配给标量。这导致分配数组的长度。在您尝试取消引用标量之前,问题不会出现,此处:

itemIds => [@{$self->{reject_array}}]

您可能想要:

$self->{reject_array} = \@idlist;

另请注意:

itemIds => [@{$self->{reject_array}}]

可以简化为:

itemIds => $self->{reject_array}

唯一的区别是这不会复制 数组,但就此而言,这不会对您的代码产生影响。它只会使它更有效率。

参考:perldata

If you evaluate an array in scalar context, it returns the length of the array.