Why after the while loop I am only getting last row value?

后端 未结 3 752
南旧
南旧 2021-01-23 22:42

This is the files I am reading,

#Log1
Time    Src_id  Des_id  Address
0   34  56  x9870
2   36  58  x9872
4   38  60  x9874
6   40  62  x9876
8   42  64  x9878
         


        
3条回答
  •  日久生厌
    2021-01-23 23:19

    Because @fields* gets overwritten during each loop. You need this:

    while(my $line = ){
        my @tmp = split(" ", $line);
        push(@fields1, \@tmp);
    }
    foreach $item (@fields1){
        print("@{$item}\n");
    }
    

    Then @fields1 contains references pointing to the splited array.

    The final @fields1 looks like:

    @fields1 = (
       ----> ["0", "34", "56", "x9870"]
       ----> ["2", "36", "58", "x9872"]
      ...
    )
    

    The print will print:

    Time Src_id Des_id Address
    0 34 56 x9870
    2 36 58 x9872
    4 38 60 x9874
    6 40 62 x9876
    8 42 64 x9878
    

    And I guess it would be better if you do chomp($line).

    But I'd like to simply do push(@fields1, $line). And split each array item when in comparison stage.

    To compare the content of 2 files, I personally would use 2 while loops to read into 2 arrays just like what you have done. Then do the comparison in one for or foreach.

提交回复
热议问题