You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Perl脚本按冒号分割读取文件数据至数组并处理的实现方法

Solution for Reading Colon-Separated Data into Arrays in Perl

Hey there! Let's work through your Perl problem. You're looking to parse colon-separated server data into dedicated arrays so you can run tasks like finding the server with the least free disk space—let's fix your code and add that functionality.

First, let's note a couple small issues in your current code:

  • The print statement has a syntax error (extra comma before if)
  • You aren't removing newline characters from each line, which can cause weird formatting or data inconsistencies
  • You're storing each line's data in single variables instead of arrays, which limits your ability to analyze the full dataset later

Fixed Code with Array Storage

Here's a revised version of your script that stores each data field in its own array, fixes the syntax issues, and includes the "find smallest free disk" functionality you mentioned:

#!/usr/bin/perl
use warnings;
use diagnostics;
use v5.26.1;

# Open the file (fixed the unnecessary double slash in path)
open (my $fh, "<", "/root/Perl/serverFile.txt") or die "System cannot find the file specified. $!";

# Prints header
sub header {
    print "Server ** CPU Util% ** Avg Mem Usage ** Free Disk\n";
    print "-------------------------------------------------\n";
}

# Define arrays to store each data category
my (@server_names, @cpu_utils, @avg_mem_usages, @disk_frees);
my $totalMem = 0;
my $count = 0;

header();

while(<$fh>) {
    chomp; # Remove newline character from the end of the line
    # Split the line into individual fields
    my ($name, $cpuUtil, $avgMemUsage, $diskFree) = split(":", $_);
    
    # Push each value into its corresponding array
    push @server_names, $name;
    push @cpu_utils, $cpuUtil;
    push @avg_mem_usages, $avgMemUsage;
    push @disk_frees, $diskFree;
    
    # Print servers with CPU >90% (fixed syntax error)
    if ($cpuUtil > 90) {
        print "$name ** $cpuUtil% ** $avgMemUsage% ** $diskFree\n\n";
    }
    
    $totalMem += $avgMemUsage;
    $count++;
}

# Calculate average memory usage (formatted to 2 decimal places for readability)
print "The average memory usage for all servers is: ", sprintf("%.2f", $totalMem / $count), "%\n";

# --- Example: Find server with smallest free disk space ---
print "\n--- Server with the smallest free disk space ---\n";
my $min_disk = $disk_frees[0];
my $min_index = 0;

for my $i (1..$#disk_frees) {
    if ($disk_frees[$i] < $min_disk) {
        $min_disk = $disk_frees[$i];
        $min_index = $i;
    }
}

print "Server: $server_names[$min_index] | Free Disk: $min_disk\n";

close $fh;

Key Changes Explained

  • Array Storage: We created four arrays (@server_names, @cpu_utils, etc.) and used push to add each line's data to the appropriate array. This lets you access all server data after parsing the file for further analysis.
  • chomp: Removes the newline character from each line, so values like $diskFree don't have invisible trailing newlines that could break comparisons or formatting.
  • Fixed Syntax: Rearranged the if condition for printing to avoid the comma error, and cleaned up the file path.
  • Added Functionality: Included a section to find the server with the smallest free disk space, showing a practical use case for the stored arrays.

How to Use the Arrays

Now that your data is stored in arrays, you can easily perform other common tasks:

  • Sort servers by CPU usage: my @sorted_by_cpu = sort { $cpu_utils[$a] <=> $cpu_utils[$b] } 0..$#server_names;
  • Filter servers with free disk below a threshold: my @low_disk_servers = grep { $disk_frees[$_] < 10000 } 0..$#server_names;

That should cover your needs! Let me know if you need clarification on any part.

内容的提问来源于stack exchange,提问作者Apache

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:12:07