2017-07-03 188 views
-1

我具有其中測量存儲它看起來像這樣的文本文件:Perl的保存的測量結果

sometext 
Step 1: 
tphlay = 1.5e-9 
tplhay = 4.8e-9 
tphlby = 1.01e-8 
tplhby = 2.4e-10 

Step 2: 
tphlay = 2.5e-9 
tplhay = 1.8e-9 
tphlby = 6.01e-8 
tplhby = 1.4e-10 
... 

與多個測量(tphlay,...)的每個步驟和具有多個值,以各測定在不同的步驟。該腳本應該能夠將任何度量值的所有值保存在不同的數組中,如arraytphlay = [1.5e-9,2.5e-9]等等。

每一步都會有相同的測量值。 其中一個問題是測量的名稱是可變的,並且取決於以前運行的腳本。但是我創建了一個包含這些名稱的數組(namearray)。 我的想法是爲namearray的每個元素創建一個數組,但我已經讀過這是不好的做法,因爲它使用軟引用,而應該使用散列代替。但對於哈希我讀過,你不能分配多個值到一個鍵。

因此,我想知道如何以智能的方式保存這些測量結果,我會爲你做一個代碼示例,因爲我僅僅是一個perl初學者。

回答

1

您可以將對數組的引用存儲爲散列鍵的值。要推動它,取消對它的引用先用@{ ... }

#!/usr/bin/perl 
use warnings; 
use strict; 

my %measurement; 

while (<>) { 
    if (my ($key, $value) = /(\w+)\s*=\s*([0-9.e+\-]+)/) { 
     push @{ $measurement{$key} }, $value; 
    } 
} 

use Data::Dumper; print Dumper \%measurement; 

輸出:

$VAR1 = { 
      'tphlay' => [ 
         '1.5e-9', 
         '2.5e-9' 
         ], 
      'tplhay' => [ 
         '4.8e-9', 
         '1.8e-9' 
         ], 
      'tphlby' => [ 
         '1.01e-8', 
         '6.01e-8' 
         ], 
      'tplhby' => [ 
         '2.4e-10', 
         '1.4e-10' 
         ] 
     }; 
1

但是對於哈希我已經讀過,您不能將多個值分配給 一鍵。

確實如此,但這並不意味着您無法將數據結構關聯到關鍵字。你可能需要的是數組引用。只給你一個想法:

my @array = (1, 2, 3); 
# First element of the array 
$array[0]; 

# $arrayref can be thought as a pointer to an anonymous array. 
# $arrayref is called a *reference* 
my $arrayref = [ 1, 2, 3 ]; 
# First element of the anonymous array $arrayref points to. 
# The -> operator is used to dereference $arrayref, to access 
# that array. 
$arrayref->[0]; 

通知(這是對你問題的有趣之處)$arrayref是標量值,因此適合用來作爲哈希值。例如:

my %hash = (
    tphlay => [ 1.5e-9, 2.5e-9 ] 
    ... 
); 

我建議你閱讀perldata。熟悉參考資料以及如何操作它們是Perl編程的支柱之一。