【问题标题】:Iterating through a Perl array from an AJAX request从 AJAX 请求遍历 Perl 数组
【发布时间】:2017-01-23 19:04:56
【问题描述】:

我正在开发一个 Catalyst 数据库项目并尝试通过 jQuery 执行一些 AJAX 请求。参数发送正常,如图 1 所示。

请注意,“diagnosis”和“type_consents”(及其对应的日期)均作为值数组(值 1、值 2、...值 n)发送。

现在对于服务器端处理,Catalyst::Request 允许通过$req->parameters 轻松检索数据,但它似乎对我不起作用。

我是这样做的:

my $params = $c->request->parameters; #Retrieving all parameters

my @type_consents         = $params->{type_consent};
my @date_consents         = $params->{date_consent};
my @diagnosis             = $params->{diagnosis};
my @date_diagnosis        = $params->{date_diagnosis};

然后我需要循环这些数组并为每对值 (diagnosis|date , consent|date) 进行插入。另外,我需要存储和处理所有事务并在eval() 块中一次执行它们,所以我这样做:

my %transactions;

# Diagnosis
my $diag_index = 0;

foreach my $key ( 0 .. $#diagnosis ) {
    $transactions{diagnosis}{$diag_index} = $diagnosis_mod->new(
        {
            subject_id          => $subject_id,
            diagnosis_date      => $date_diagnosis[$key],
            diagnosis           => $diagnosis[$key],
            diagnosis_comment   => "",
            suggested_treatment => ""
        }
    );

    print STDERR "\n" . $date_diagnosis[$diag_index];
    print STDERR "\n DEBUG: $date_diagnosis[$diag_index] | $diagnosis[$diag_index] | key: $diag_index";
    print STDERR "\n DEBUG2:" . Dumper( @date_diagnosis ) . " | " . Dumper( @diagnosis );

    $diag_index++;
}

# I'm avoiding evaluating and performing the transactions so neither eval() nor database impact are shown above.

这些调试会打印以下内容:

这是否表明我的“数组”只是一个带有字符串的一维变量?我试过拆分它,但也没有用。

【问题讨论】:

    标签: arrays perl catalyst


    【解决方案1】:

    您可以存储在哈希中的唯一值是标量。因此,$params->{type_consent} 是一个标量,而不是一个列表。但是,由于对事物(标量、数组、散列、对象、glob 等)的引用也是标量,因此您可以将引用存储在散列中。

    因此,$params->{type_consent} 是对数组的引用,而不是数组或列表本身。

    然后,我认为您想要的是将其分配给 my $type_consent = $params->{type_consent};,然后使用 @$type_consent 作为您的数组(因此它们都指向同一个数组 - 通过 @$type_consent 更改某些内容会更改该数组%$params),通过说my @type_consent = @{$params->{type_consent}};复制数组。

    我选择使用哪一个是视情况而定的,但如果只是为了在没有理由复制它的情况下降低内存使用率,我倾向于使用参考选项。

    【讨论】:

    • 两者都做得很好。非常感谢,@Tanktalus。我个人认为第二个选项更容易阅读,所以我会选择那个,但两者都有效:)
    • 我正在做一些测试,似乎只有在发送 2 个或更多元素时才能正常工作。每当发送 1 个元素(请求可接受的最小值)时,我都会收到此错误:[error] Caught exception in pbitdb::Controller::Subjects->add "Can't use string ("1") as an ARRAY ref while "strict refs" in use at /home/lioneluranl/svn/pbitdb/pbitdb/script/../lib/pbitdb/Controller/Subjects.pm line 119." ... 在这种情况下,“1”是发送的值...并且引用的行是我声明列表的行:@ 987654329@有什么想法吗?
    • IMO,拥有动态类型的设计很糟糕 - 可以具有标量值数组(引用)值的键。但是,如果您调用的 API 不在您的控制之下,您可能必须在代码中处理它:my @type_consent = ref $params->{type_consent} ? @{$params->{type_consent}} : $params->{type_consent}; 类似作为参考:my $tc = ref $params->{type_consent} ? $params->{type_consent} : [ $params->{type_consent} ]
    • 是的...不幸的是 API 就是这样工作的 :( 。我什至不知道我可以在 perl 中做“任何一种”的事情。非常感谢。
    猜你喜欢
    • 2018-07-14
    • 2011-01-29
    • 1970-01-01
    • 2021-12-06
    • 2013-12-11
    • 1970-01-01
    • 1970-01-01
    • 2017-07-05
    • 2015-11-21
    相关资源
    最近更新 更多