[英]Perl - “Complex” Data Structure
我試圖獲得一個可行的數據結構,以一種明智的方式從中獲取元素值。 一旦在結構中處理數據就很難了。 這是結構的構建方式:
sub hopCompare
{
my %count;
my %master;
my $index = 0;
foreach my $objPath (@latest) #get Path object out of master array
{
my @path = @{$objPath->_getHopList()}; #dereferencing
my $iter = 0;
foreach my $hop (@path)
{
++$count{$hop}->{FREQ};
$count{$hop}->{INDEX} = $index;
$count{$hop}->{NODE} = $hop;
$index++;
}
$index = 0;
}
foreach my $element( keys %count )
{
if (defined($count{$element}->{NODE}))
{
my $curr = $count{$element}->{INDEX};
my $freq = $count{$element}->{FREQ};
if (($freq > 1) || ($count{$element}->{INDEX} =~ /[0-1]/))
{
push @{ $master{$curr} }, {$count{$element}->{NODE}, {FREQ => $count{$element}->{FREQ}}};
}
print "$element = $count{$element}\n";
print "$element Index = $count{$element}->{INDEX}\n";
}
}
print "\n Master contains: \n" . Dumper (%master);
if (%master){return %master;} else {die "NO FINAL HOPS MATCHED";}
}
產生這種結構:
%Master包含:
$VAR1 = '4';
$VAR2 = [
{
'1.1.1.2' => {
'FREQ' => 2
}
}
];
$VAR3 = '1';
$VAR4 = [
{
'1.1.1.9' => {
'FREQ' => 5
}
},
{
'1.1.1.8' => {
'FREQ' => 1
}
}
];
{truncated}
雖然理想情況下該結構應如下所示,但是嘗試在子identifyNode上提取數據時,我的喜悅甚至更少:
$VAR1 = {
'1' => [
{
'1.1.1.9' => {
'FREQ' => 5
}
},
{
'1.1.5.8' => {
'FREQ' => 1
}
}
],
然后使用另一種方法來獲取數據:
sub identifyNode
{
my %hops = %{$_[0]};
my $i = 0;
foreach my $h ( keys %hops ) #The HOP-INDEX is the key
{
print "\n\$h looks like \n" . Dumper ($hops{$h});
my %host = %{ $hops{$h}[0] }; #Push the first HASH in INDEX to the %host HASH
foreach my $hip (keys %host)
{
my $corelink = `corelinks $hip`;
my ($node) = $corelink =~ /([a-z0-9-]+),[a-z0-9-\/]+,$hip/s;
print "\n\t\t\tHostname is $node\n";
}
$i++;
}
}
然后生成:
$h looks like
$VAR1 = [
{
'1.1.1.2' => {
'FREQ' => 2
}
}
];
Hostname is blabla-bla-a1
$h looks like
$VAR1 = [
{
'1.1.1.9' => {
'FREQ' => 5
}
},
{
'1.1.1.8' => {
'FREQ' => 1
}
}
];
Hostname is somew-some-a1
因此,對於$ h中的每個哈希,只會評估最頂層的主機,並返回主機名。 這是因為第[0]行告知這樣做:
my %host = %{ $hops{$h}[0] };
我研究了不同的數據結構,並以多種方式取消引用該結構,這是我發現的唯一中途之家...
(IP已被混淆,因此在我的示例中不一致)
感謝您的建議,這使我半途而廢。 現在它可以工作了(仍然有些復雜!):
sub identifyNode
{
my %hops = %{$_[0]};
my $i = 0;
my @fin_nodes;
my $hindex;
foreach my $h ( keys %hops ) #The HOP-INDEX is the key
{
$hindex = $h;
foreach my $e (@{$hops{$h}}) #first part of solution credit Zdim
{
my @host = %{ $e }; #second part of solution
my $hip = $host[0];
my $corelink = `corelinks $hip`;
my ($node) = $corelink =~ /([a-z0-9-]+),[a-z0-9-\/]+,$hip/s;
print "\n\t\t\tHostname is $node\n";
push (@fin_nodes, [$node, $hindex, $e->{$hip}->{FREQ}]);
}
$i++;
}
return (\@fin_nodes);
}
我足夠勇敢地將數據作為哈希添加到@fin_nodes .. hmm
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.