1

所以我目前正在处理一个 perl 项目,我需要将一个数组(包含要拒绝的 ID)作为哈希引用传递给另一个子节点,在该子节点中我访问该数组,并在我正在创建的 json 文件中使用它的内容。我目前希望将数组作为 ref 存储在我的主哈希中;“$self”我在潜艇之间夹着,以便访问我用来获得身份验证的令牌。对于我正在处理的网站:

#!/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 文件中,然后显然不起作用)。

对此的任何帮助将不胜感激 - 我无法在其他地方找到解决方案。

4

1 回答 1

4

这里:

$self->{reject_array} = @idlist;

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

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

您可能想要:

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

另请注意:

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

可以简化为:

itemIds => $self->{reject_array}

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

参考:perldata

如果在标量上下文中计算数组,它会返回数组的长度。

于 2019-10-20T16:36:33.680 回答