繁体   English   中英

我如何在Perl中将文件中的行读入哈希

[英]How do i read lines from a file into a hash in Perl

我正在使用一种包含以下信息行的文件格式:

原子1 N溶酶A 56 20.508 14.774 -7.432 1.00 50.83 N

我想要的只是第一个数字,在上面的示例中,三个数字紧跟着“ 56”; 所以即时通讯使用正则表达式来获取该信息。 然后如何将该信息放入哈希表中?

到目前为止,我有:

my $pdb_file = $ARGV[0];
open (PDBFILE, "<$pdb_file") or die ("$pdb_file not found");
while (<PDBFILE>) { 
if ($_=~ /^ATOM\s+(\d+)\s+\w+\s+\w+\s+\w+\s+\d+\s+(\d+\.\d+)\s+(\d+\.\d+)\s+(\d+\.\d+)/) {
my $atom = $1;
my $xcor = $2;
my $ycor = $3;
my $zcor = $4;
print "AtomNumber: $atom\t  xyz: $xcor $ycor $zcor\n";
}
}

我不建议使用正则表达式,而建议使用split将其拆分为空白中的字段。 这将更快,更健壮,并且不依赖于每个字段格式的详细知识(该知识可能会发生变化,例如数字是否带有负号,而您忘记了这一点)。 而且它更容易理解。

my @fields = split /\s+/, $line;

然后,您可以选择字段(例如,第一个数字是字段2,因此$fields[1] )并将其放入哈希中。

my %coordinate = (
    atom => $fields[1],
    x    => $fields[6],
    y    => $fields[7],
    z    => $fields[8]
);

您正在阅读一堆线,因此您将要创建一堆必须放在某个地方的哈希。 我建议将它们全部放入另一个散列中,并以某种唯一字段作为关键字。 可能是atom场。

$atoms{$coordinate{atom}} = \%coordinate;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM