[英]In Perl, how can I print lines read from a file with optional leading whitespace removed?
[英]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.