数组意外输出

时间:2017-04-03 07:27:31

标签: arrays perl

这是我的剧本:

package javaapplication3;
public class LIstTEst {
    Node head;
    static class Node{
        int data;
        Node next;
        Node(int d){
            data = d;
            next = null;
        }
    }

    public void PrintList(){
        Node n = head;
        while(n != null){
            System.out.print(n.data+" ");
            n = n.next;
        }
    }
    public static void main(String args[]){
        LIstTEst llist = new LIstTEst();
        llist.head = new Node(1);
        Node second = new Node(2);
        Node third = new Node(7);

        llist.head.next = second;
        second.next = third; = third;

        llist.PrintList();
    }
}

输出:

#!/usr/bin/perl
use strict;
use warnings;
use Web::Scraper;
use Data::Dumper;
use URI;
my $purlToScrape='http://www.natboard.edu.in/dnbfinal.php';
my $webdata = scraper {      
      process 'td.noticeboard', "data[]" => 'TEXT';      
  };
my $dnbnotices = $webdata->scrape(URI->new($purlToScrape));
my @noticeboard=$dnbnotices->{data};
print ref @noticeboard."\n\n";
print Dumper(@noticeboard);
print scalar @noticeboard."\n";
for my $notice ( @noticeboard ) {
    if ($notice) {
        print $notice."\n";
    }    
}
print $noticeboard[1];

问题:

  1. 为什么裁判没有打印出“ARRAY”?
  2. 为什么数组计数显示为1?它不是单个元素阵列。
  3. 为什么数组的元素没有打印出来?
  4. 为什么 $VAR1 = [ 'December - 2016 ', 'DNB Final December -2016', '30th September, 2016', '', '', 'JUNE - 2016 ', 'DNB Final JUNE -2016', '15th May, 2016', '', '', 'Dec - 2015 ', 'DNB Final Dec -2015', '9th October, 2015', '', '', 'June - 2015 ', 'DNB Final June -2015', '6th May, 2015', '', '', 'December - 2014 ', 'DNB Final December - 2014', '30th September, 2014', '', '' ]; 1 ARRAY(0x4521bd8) Use of uninitialized value in print at ./test1.pl line 21. 未初始化?

1 个答案:

答案 0 :(得分:4)

1- ref在调用除了ref之外的其他内容时返回空字符串。因此,在执行ref @xxx时,除了空字符串之外,您不能指望任何其他内容 此外,ref @noticeboard."\n\n"ref ((scalar @noticeboard)."\n\n")相同,即ref "1\n\n",返回空字符串。

2-3-4- scrape返回了一个数组引用,而不是数组。因此,在将其分配给数组(my @noticeboard=$dnbnotices->{data})时,它会进入第一个元素。 (事实上​​,数组只有一个元素是数组引用,解释了你的问题2,3和4)。

您的脚本应该是:

#!/usr/bin/perl
use strict;
use warnings;
use Web::Scraper;
use Data::Dumper;
use URI;
my $purlToScrape='http://www.natboard.edu.in/dnbfinal.php';
my $webdata = scraper {      
      process 'td.noticeboard', "data[]" => 'TEXT';      
  };
my $dnbnotices = $webdata->scrape(URI->new($purlToScrape));
my $noticeboard=$dnbnotices->{data};
print "ref=",ref($noticeboard),"\n\n";
print "dumper:",Dumper($noticeboard);
print "nb elements:",scalar @$noticeboard,"\n";
print "content:\n";
for my $notice ( @$noticeboard ) {
    if ($notice) {
        print "  ",$notice,"\n";
    }    
}
print "first element:",$noticeboard->[1];

另外,您可以使用say代替print ... "\n",这样会更方便。 (但您需要use feature 'say'use v5.10或更高版本。)

如果您需要有关参考文献的更多参考资料,请参阅perlrefperlreftut