首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将文件中的数据读入数组,以便在Perl脚本中进行操作

将文件中的数据读入数组,以便在Perl脚本中进行操作
EN

Stack Overflow用户
提问于 2018-05-28 02:54:33
回答 1查看 480关注 0票数 2

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;
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50555476

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档