Search code examples
perlhashmeasurement

Perl save measurement results


i have a text file in which measurements are stored which looks like this:

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
...

with multiple measurements (tphlay, ...) to each step and with multiple values to each measurement in the different steps. The script should be able to save all values for any measurement in a different array like arraytphlay = [1.5e-9, 2.5e-9] and so on.

Every step will have the same measurements. One of the problems is that the names of the measurements are variable and depend on previously run scripts. But i have created an array (namearray) which contains these names. My idea was to create one array for every element of namearray but i have read that this is bad practice since it uses soft references and that you should use hashes instead. But for hashes i have read that you cannot assign multiple values to one key.

Therefore i would like to know how to save these measurements in an intelligent way and i you would be so kind maybe a code example since i am merely a beginner in perl.


Solution

  • You can store a reference to an array as a value for a hash key. To push to it, dereference it first with the @{ ... }:

    #!/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;
    

    Output:

    $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'
                          ]
            };