3

Getting an error when I attempt to dump out part of a multi dimensional hash array. Perl spits out

Can't use string ("somedata") as an ARRAY ref while "strict refs" in use at ./myscript.pl

I have tried multiple ways to access part of the array I want to see but I always get an error. I've used Dumper to see the entire array and it looks fine.

#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper qw(Dumper);
use String::Util qw(trim);

my %arrHosts;

open(my $filehdl, "<textfile.txt") || die "Cannot open or find file textfile.txt: $!\n";

while( my $strInputline = <$filehdl> ) {
  chomp($strInputline);
  my ($strHostname,$strOS,$strVer,$strEnv) = split(/:/, $strInputline);
  $strOS = lc($strOS);
  $strVer = trim($strVer);
  $strEnv = trim($strEnv);
  $strOS = trim($strOS);
  $arrHosts{$strOS}{$strVer}{$strEnv} = $strHostname;
}

# If you want to see the entire database, remove the # in front of Dumper
print Dumper \%arrHosts;

foreach my $machine (@{$arrHosts{solaris}{10}{DEV}}) {
  print "$machine\n";
}

close($filehdl);

The data is in the form machine:OS:OS version:Environment

For example

bigserver:solaris:11:PROD
smallerserver:solaris:11:DEV

I want to print out only the servers that are solaris, version 11, in DEV. Using hashes seems the easiest way to store the data but alas, Perl barfs when attempting to print out only a portion of it. Dumper works great but I don't want to see everything. Where did I go wrong??

4

2 回答 2

3

您有以下内容:

$arrHosts{$strOS}{$strVer}{$strEnv} = $strHostname;

这意味着以下内容包含一个字符串:

$arrHosts{solaris}{10}{DEV}

您将其视为包含对数组的引用。要按 OS+ver+env 对主机进行分组,请替换

$arrHosts{$strOS}{$strVer}{$strEnv} = $strHostname;

push @{ $arrHosts{$strOS}{$strVer}{$strEnv} }, $strHostname;

然后迭代@{ $arrHosts{solaris}{10}{DEV} }将是有意义的。

于 2019-10-24T17:09:17.833 回答
0

我之前的代码也有一个明显的问题,如果操作系统、版本和环境的组合相同,它会覆盖之前的数据。大错特错。推是诀窍

于 2019-10-24T17:52:36.530 回答