gpt4 book ai didi

arrays - 将数据从文件读取到数组中以在 Perl 脚本中进行操作

转载 作者:行者123 更新时间:2023-12-01 23:29:45 26 4
gpt4 key购买 nike

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;

最佳答案

对于这个用例,哈希比数组好得多。

#!/usr/bin/perl
use strict;
use feature qw{ say };
use warnings;

use List::Util qw{ min };

my %server;
while (<>) {
chomp;
my ($name, $cpu_utilization, $avg_memory, $disk_free)
= split /:/;
@{ $server{$name} }{qw{ cpu_utilization avg_memory disk_free }}
= ($cpu_utilization, $avg_memory, $disk_free);
}

my $least_disk = min(map $server{$_}{disk_free}, keys %server);
say for grep $server{$_}{disk_free} == $least_disk, keys %server;

关于arrays - 将数据从文件读取到数组中以在 Perl 脚本中进行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50555476/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com