向多维数组的内层数组添加元素不起作用

编程语言 2026-07-08

在下面的代码中,我创建了两个空的数组组成的数组。虽然我能够向第一个数组填充数据,但对第二个数组相同的方法却不起作用。

在一个以 $i为循环变量的循环中,push $riskcols[$i]->@*, $columns[$i]; 可以工作。

另一个循环,同样以 $i进行的循环中,push @{$riskhrs[$i]->@*}, \@temparry; 不起作用。

我尝试了来自不同帖子中关于 push 命令的几种变体,但都不成功。

#!/usr/bin/perl

 use 5.40.1; 
 use strict;
 use warnings;
 use Data::Dump;
 use List::Util qw(min max);

 my @riskcols;
 my $riskcols;
 my @riskhrs;
 my $riskhrs;

 @riskcols=map { [] } 1..2;
 @riskhrs=map { [] } 1..2;

 #while (my $line = <$in>){
 while (my $line = <DATA>){
  chomp($line); # Remove trailing newline character

  #Split the line by delimiter (e.g., \t for tabs, ',' for CSV, or \s+ for spaces)
  #*******************************************************************************
  my($num, $lon, $lat, $ihr, @columns) = split(/\s+/, $line);

  #Extract the first column (Index 0). Change the index to get a different column.
  #*******************************************************************************
   if(@columns){ 
    foreach my $i (0..$#riskcols){
     if($columns[$i] ne -9){
      push $riskcols[$i]->@*, $columns[$i];
     }
    }
   }
  }

  my $i=0;
  foreach my $inner_array (@riskcols){
   next unless @$inner_array;            # Skip empty arrays to avoid warnings
   my $minhr = min(@$inner_array);
   my $maxhr = max(@$inner_array);
   my @temparry=($minhr, $maxhr);
   print "@temparry\n";
   #exit;
   push @{$riskhrs[$i]->@*}, \@temparry;

   print "Inner Array: [@$inner_array] -> Min: $minhr, Max: $maxhr\n";
   $i++
  }
  print "@riskhrs\n";
  print "$riskhrs[0]\n";
  print "$riskhrs[1]\n";
  print "Column extraction complete!\n";

 __DATA__
99956  28.36  -28.90  1     -9     -9     -9     -9
99957  29.09  -29.04  1     15     -9     -9     -9
99958  28.87  -29.06  1     15     -9     -9     -9
99959  28.14  -28.81  1     -9     -9     -9     -9
99960  28.19  -28.78  1     -9     -9     -9     -9
99961  28.34  -28.79  1     -9     -9     -9     -9
99962  28.63  -28.87  1     18     -9     -9     -9
99963  28.40  -28.76  1     -9     -9     -9     -9
99964  28.54  -28.66  1     -9     10     -9     -9
99965  27.67  -30.41  1     -9     11     -9     -9
99904  27.49  -30.30  1     -9     11     -9     -9
99905  27.69  -30.24  1     -9     -9     -9     -9
99906  28.09  -30.25  1     -9     -9     -9     -9
99907  28.21  -30.16  1     -9     -9     -9     -9
99908  27.40  -30.08  1     -9     09     -9     -9
99909  28.42  -30.08  1     -9     -9     -9     -9

输出:

15 18
Can't use string ("0") as an ARRAY ref while "strict refs" in use at a.pl line 44, <DATA> line 16.

解决方案

@{$riskhrs[$i]->@*} 没有意义。在标量上下文中,$riskhrs[$i]->@* 返回所引用数组中的元素数量。接着你尝试对它进行解引用。请使用 @{$riskhrs[$i]}$riskhrs[$i]->@*

不过你其实想要的是

$riskcols[$i] = \@temporary;

或者

push @riskcols, \@temporary;
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章