在Perl中将整个文件读入哈希 [英] Reading an entire file into a hash in Perl

查看:623
本文介绍了在Perl中将整个文件读入哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将文件读入Perl的哈希中时遇到一些问题.

I have some problems reading a file into a hash in Perl.

Chr1_supercontig_000000000  1   500
    PILOT21_588_1_3_14602_59349_1
Chr1_supercontig_000000001  5   100
    PILOT21_588_1_21_7318_90709_1
    PILOT21_588_1_43_18803_144592_1
    PILOT21_588_1_67_13829_193943_1
    PILOT21_588_1_42_19678_132419_1
    PILOT21_588_1_67_4757_125247_1
...

所以我上面有这个文件.我想要的输出是一个散列,其中"Chr1"行为键,而"PILOT"行为值.

So I have this file above. My desired output is a hash with the "Chr1"-lines as key, and the "PILOT"-lines as values.

Chr1_supercontig_000000000 => PILOT21_588_1_3_14602_59349_1
Chr1_supercontig_000000001 => PILOT21_588_1_21_7318_90709_1, PILOT21_588_1_43_18803_144592_1,...

据我所知,只能通过引用将多个值分配给一个键,对吗?

As far as I know, multiple values can be assigned to a key only by reference, is that correct?

我现在被困住了,需要帮助.

I got stuck at this point and need help.

推荐答案

是的,哈希值必须是指向包含PILOT行的数组的引用.

You are right, the hash values need to be references that point to arrays which contain the PILOT lines.

这是一种方法:

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;

这篇关于在Perl中将整个文件读入哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆