我有一个文本文件,其中存储的测量值如下所示:
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的初学者。
答案 0 :(得分: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编程的支柱之一。
答案 1 :(得分: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'
]
};