Perl新手。我需要弄清楚如何从一个用(:)分隔的文件读入一个数组。然后我就可以操纵数据了。
这是一个'serverFile.txt‘文件的示例(刚刚加入了随机的#)字段是:名称: CPU使用率: avgMemory使用率:磁盘可用
Server1:8:6:2225410
Server2:75:68:64392
Server3:95:90:12806
Server4:14:7:1548700
我想弄清楚如何将每个字段放入其相应的数组中,然后在其上执行函数。例如,查找可用磁盘空间最少的服务器。
我现在设置它的方式,我不认为它会工作。那么,如何将每行中的每个元素放入一个数组中呢?
#!usr/bin/perl
use warnings;
use diagnostics;
use v5.26.1;
#Opens serverFile.txt or reports and error
open (my $fh, "<", "/root//Perl/serverFile.txt")
or die "System cannot find the file specified. $!";
#Prints out the details of the file format
sub header(){
print "Server ** CPU Util% ** Avg Mem Usage ** Free Disk\n";
print "-------------------------------------------------\n";
}
# Creates our variables
my ($name, $cpuUtil, $avgMemUsage, $diskFree);
my $count = 0;
my $totalMem = 0;
header();
# Loops through the program looking to see if CPU Utilization is greater than 90%
# If it is, it will print out the Server details
while(<$fh>) {
# Puts the file contents into the variables
($name, $cpuUtil, $avgMemUsage, $diskFree) = split(":", $_);
print "$name ** $cpuUtil% ** $avgMemUsage% ** $diskFree% ", "\n\n", if $cpuUtil > 90;
$totalMem = $avgMemUsage + $totalMem;
$count++;
}
print "The average memory usage for all servers is: ", $totalMem / $count. "%\n";
# Closes the file
close $fh;
https://stackoverflow.com/questions/50555476
复制相似问题