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

Perl读取文本文件到哈希并访问值的问题求助

如何将缩进格式的文本读取到Perl哈希并正确访问值

我尝试将文本文件内容读取到Perl哈希中,但在读取和访问哈希值时遇到问题。

文本文件格式

resctrl_top
    /path/to/a/
vdm05top
    /path/to/b/
    /path/to/c/
    /path/to/d/
    /path/to/e/
    /path/to/f/

期望的哈希结构

以无前置空格的行作为键,其下缩进的路径行作为对应值,示例如下:

resctrl_top => /path/to/a/
vdm05top => /path/to/b/,/path/to/c/,/path/to/d/,/path/to/e/,/path/to/f/

我尝试的代码

use strict;
use warnings;
my %hash;
open FILE, "filename.txt" or die $!;
my $key;
while (my $line = <FILE>) {
     chomp($line);
     if ($line !~ /^\s/) {
        ($key) = $line =~ /^\S+/g;
        $hash{$key} = [];
     } else {
        $line =~ s/^\s+//;
        push @{ $hash{$key} }, $line;
     }
 }
 close FILE;

 foreach (keys %hash){
    print "$key => $hash{$key}\n";
 }

问题分析与修正

你的代码核心逻辑没问题,但输出部分有两处错误:

  1. 循环遍历哈希键时,误用了外部的$key变量,而非当前循环的键;
  2. 直接打印数组引用$hash{$key}只会输出内存地址,无法显示实际路径值。

另外建议改用词法文件句柄(my $fh),比全局文件句柄更安全规范。修正后的代码如下:

use strict;
use warnings;
my %hash;
# 改用词法文件句柄,更安全
open my $fh, '<', 'filename.txt' or die $!;
my $current_key;
while (my $line = <$fh>) {
    chomp($line);
    # 跳过空行(避免处理无效内容)
    next if $line =~ /^\s*$/;
    if ($line !~ /^\s/) {
        # 无缩进行直接作为键,无需多余正则
        $current_key = $line;
        $hash{$current_key} = [];
    } else {
        # 移除前置空格后加入对应数组
        $line =~ s/^\s+//;
        push @{ $hash{$current_key} }, $line;
    }
}
close $fh;

# 正确输出哈希内容
foreach my $key (keys %hash) {
    # 将数组元素用逗号连接成字符串
    my $paths_str = join(',', @{ $hash{$key} });
    print "$key => $paths_str\n";
}

哈希值的访问方法

  1. 获取单个键的所有路径:
    通过数组引用取出对应数组,可直接遍历或转成字符串:

    # 获取resctrl_top对应的路径数组
    my @resctrl_paths = @{ $hash{'resctrl_top'} };
    # 逐行打印路径
    print "resctrl_top的路径:\n";
    print "$_\n" for @resctrl_paths;
    
  2. 遍历所有键值对:
    除了foreach遍历键,还可以用each函数直接获取键和数组引用:

    while (my ($key, $paths_ref) = each %hash) {
        print "$key 对应的路径:", join(', ', @$paths_ref), "\n";
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 00:10:14