【问题标题】:Working with child nodes in subroutine (XML::LibXML)在子例程中使用子节点 (XML::LibXML)
【发布时间】:2014-12-31 09:33:15
【问题描述】:

在我的一小段代码中,我解析了一些 XML 数据,但是由于我需要在 3 个地方做同样的事情,所以我想为每次做一个子例程。但是我需要将我正在处理的当前节点作为参数传递,超出了我目前的技能来访问当前节点的子节点。

这是我的代码示例:

foreach $day ($doc->findnodes('/my/current/path')) {

  @atts = $day->getAttributes();

  foreach $at (@atts) {

    $na = $at->getName();
    $va = $at->getValue();

    if ($va eq "today") {

      #------ my repeated code begins here -----
      foreach $thing ($day->findnodes('child_nodes_im_looking_for')) {

        #----- do a lot of stuff
      }

      #------ my repeated code ends here -----
    }

    if ($va eq "tomorrow") {

      #same repeated code
    }

    if ($va eq "some_other_day") {

      #same repeated code.... again
    }

    #for other days... do nothing

  }

我应该如何将当前节点传递给子例程,以便我可以直接从例程访问其子节点?

【问题讨论】:

    标签: xml perl


    【解决方案1】:

    我相信你有use strictuse warnings 有效?即使你有,你也应该尽可能用my 声明你的变量为late,最好是在它们的第一个使用点。

    我不清楚到底是什么问题,从表面上看,您只需将节点$day 作为普通子程序参数传递即可。

    您的代码示例的重构显示了这个想法。如果我误解了你,请说出来。

    for my $day ($doc->findnodes('/my/current/path')) {
    
      my @atts = $day->getAttributes();
    
      for my $att (@atts) {
    
        my $na = $att->getName;
        my $va = $att->getValue;
    
        if ($va eq 'today') {
          repeated_code($day);
        }
    
        if ($va eq 'tomorrow') {
          repeated_code($day);
        }
    
        if ($va eq 'some_other_day') {
          repeated_code($day);
        }
    
        # for other days... do nothing
    
      }
    }
    
    sub repeated_code {
      my ($node) = @_;
    
      for my $thing ($node->findnodes('child_nodes_im_looking_for')) {
    
        #----- do a lot of stuff
      }
    
    }
    

    【讨论】:

    • 为什么我看到答案后总觉得我的问题有多愚蠢? ... 叹息... 感谢您清除它,我还注意到我应该使用以下行来清理代码:if (($va eq 'today') || ($va eq 'tomorrow') || ($va eq 'some_other_day')) { repeated_code($day); }
    • @Ockie:责备自己是错误的:没有愚蠢,除非是故意的
    猜你喜欢
    • 1970-01-01
    • 2013-03-31
    • 2014-10-12
    • 1970-01-01
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    相关资源
    最近更新 更多