需要帮助在 perl 中填充结构数组

ice*_*old 1 arrays perl struct

我需要一些帮助来填充由 perl 中的结构组成的数组。

数组的数据来自具有以下格式的 .SH 文件:

108,Country,Location,ap17,ip_149,ssh,model,12/8/2020
Run Code Online (Sandbox Code Playgroud)

我使用的代码如下:

use strict;
use warnings;
use Class::Struct;

struct(Net_Node => [hostname => '$', dir_ip => '$', access => '$', user => '$', pass => '$']);

my $node = Net_Node->new();
my @nodes;

my $user = "hjack";
my $pass = 'butstalion';

my $line;
my @all;

my $counter=0;

open(my $fh, '<', "exaple.sh") or die "Failed to open especified file";
#system('clear');

foreach $line (<$fh>) {

        @all=split(',', $line);


        $node->hostname ($all[3]);
        $node->dir_ip ($all[4]);
        $node->access ($all[5]);
        $node->user ($user);
        $node->pass ($pass);

        $nodes[$counter] = $node;

        $counter++;
}

my $size = @nodes;

print "\n \n";
print ("array size = $size\n\n");
$counter = 0;

while ($counter < 20) {
        print ($counter,"\n\n");    
        print ($nodes[$counter]->hostname,"\n");
        print ($nodes[$counter]->dir_ip, "\n");
        print ($nodes[$counter]->access, "\n");
        print ($nodes[$counter]->user, "\n");
        print ($nodes[$counter]->pass, "\n\n");

        $counter++;
}

close($fh);

Run Code Online (Sandbox Code Playgroud)

此代码的输出是一个填充数组,但仅包含 foreach 循环中生成的最后一个元素,是否有任何方法可以使用 .SH 文件的数据填充此数组?

提前致谢

文件的数据如下

89,Country,Location,sw01,ip_10,ssh,model,12/8/2020
90,Country,Location,sw02,ip_18,ssh,model,12/8/2020
91,Country,Location,sw03,ip_26,ssh,model,12/8/2020
92,Country,Location,sw04,ip_27,ssh,model,12/8/2020
93,Country,Location,sw05,ip_28,ssh,model,12/8/2020
94,Country,Location,sw06,ip_29,ssh,model,12/8/2020
95,Country,Location,ap02,ip_13,ssh,model,12/8/2020
96,Country,Location,ap03,ip_12,ssh,model,12/8/2020
97,Country,Location,ap04,ip_20,ssh,model,12/8/2020
98,Country,Location,ap05,ip_14,ssh,model,12/8/2020
99,Country,Location,ap06,ip_15,ssh,model,12/8/2020
100,Country,Location,ap07,ip_16,ssh,model,12/8/2020
101,Country,Location,ap08,ip_17,ssh,model,12/8/2020
102,Country,Location,ap09,ip_18,ssh,model,12/8/2020
103,Country,Location,ap10,ip_19,ssh,model,12/8/2020
104,Country,Location,ap11,ip_24,ssh,model,12/8/2020
105,Country,Location,ap12,ip_25,ssh,model,12/8/2020
106,Country,Location,ap14,ip_27,ssh,model,12/8/2020
107,Country,Location,ap15,ip_37,ssh,model,12/8/2020
108,Country,Location,ap17,ip_149,ssh,model,12/8/2020
Run Code Online (Sandbox Code Playgroud)

mob*_*mob 5

my $node = Net_Node->new();
...
foreach $line (<$fh>) {
   ...
   $nodes[$counter] = $node;
}
Run Code Online (Sandbox Code Playgroud)

创建单个Net_Node实例并在循环的每次迭代中覆盖其数据foreach。听起来您想为循环的每一行创建一个新实例。所以你应该将你的Net_Node->new()调用移到循环内。

foreach $line (<$fh>) {
   my $node = Net_Node->new();
   ...
   $nodes[$counter] = $node;
}
Run Code Online (Sandbox Code Playgroud)

使用更简单的数据结构(例如本机 Perl 哈希),您可以将数据结构的副本附加到列表中,例如

   $nodes[$counter] = { %$node };
Run Code Online (Sandbox Code Playgroud)

但我更不愿意对对象执行此操作,该对象甚至可能不会在内部表示为哈希引用。