Perl split and array

Hello, I have the following code:

 while ($line = <fd_in>) {
   126    $line = " " . $line ;
   127  print "our_line:$line\n";
   128    @list = split (/\s+/, $line) ;
   129  print "after_split:@list\n";
   130  print "$list[0]\t$list[1]\t$list[2]\t$list[3]\t$list[4]\t$list[5]$list[6]\t\n";
   131    $len = $#list ;
   132  print "length of array:$len\n";
   133
   134
   135    if (($len >= 7) && ($list[3] ne "total")) { # Ignore header and totals
   136      $cpu_id = $list[2] ;
   137      print "$list[0]\t$list[1]\t$list[2]\t$list[3]\t$list[4]\n";
   138      print "cpu_id: $cpu_id\n";
   139      $pic0 = $list[4] ;
   140      print "pic0: $pic0\n";
   141      $pic1 = $list[5] ;

And when I ran the code, here is one of the output:

our_line:   1.023  25  tick         8       635  # pic0=L2_dmiss_ld,pic1=Instr_cnt

after_split: 1.023 25 tick 8 635 # pic0=L2_dmiss_ld,pic1=Instr_cnt
        1.023   25      tick    8       635#
length of array:7
        1.023   25      tick    8
cpu_id: 25
pic0: 8

What I am not getting is, line 127 is printing out the whole array and then the "split" is splitting the array based on one or more spaces (I might be wrong, but the output shows like that).
But then in the code line 130, I am trying to print all the elements of the array which is not making sense. It is not printing out all the elements.

Later, line 136 is taking cpu_id as 3rd element of the array ($list[2]), but it should be $list [1]. I am not sure how it is working and might be missing the clue.

Any help is much appreciated.

After the split() , it appears that you have 7 elements in $list[1] through $list[7] . You are printing $list[0] (which is appearing as an empty string (because it has not been set by split() ) at the start of your output lines before the first tab ( \t ) in your format string). The missing final element is not showing up because you did not print the contents of $list[7] .

Don, Zam,

$list[0] is the empty string because a space was prepended to $line on line 126.

Zam,

Perhaps a little simplification is needed:

while (<fd_in>) {
   s{\s*#.*$}{};
   ($cpu_id, $key, $pic0, $pic1) = (split)[1,2,3,4];
   next if $key eq 'total';
print 'cpuID:', $cpu_id, ' pic0:', $pic0, ' pic1:', $pic1, "\n";

Remove s{\s*#.*$}{} if '#' does not begin a comment.

2 Likes