将整个文件读入Perl中的哈希

Phi*_*ipp 3 perl hash

我在将文件读入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
...
Run Code Online (Sandbox Code Playgroud)

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

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,...
Run Code Online (Sandbox Code Playgroud)

据我所知,只能通过引用将多个值分配给一个键,这是正确的吗?

我陷入困境,需要帮助.

ale*_*exk 5

你是对的,哈希值需要是指向包含PILOT行的数组的引用.

这是一种方法:

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;
Run Code Online (Sandbox Code Playgroud)


Eug*_*ash 5

您可以逐行读取文件,跟踪当前哈希键:

open my $fh, '<', 'file' or die $!;

my (%hash, $current_key);

while (<$fh>) {
    chomp;        
    $current_key = $1, next if /^(\S+)/;
    s/^\s+//; # remove leading space
    push @{ $hash{$current_key} }, $_;
}
Run Code Online (Sandbox Code Playgroud)