timothy: Hash aus Datei auslesen

Beitrag lesen

Hi Andreas

vielleicht hilft dir ja folgendes weiter:
aus
"Programming Perl"
by Larry Wall, Tom Christiansen & Randal L. Schwartz; ISBN 1-56592-149-6, 670 pages.
Second Edition, September 1996.

<snippet>
4.7.3 Arrays of Hashes

An array of hashes is called for when you have a bunch of records that you'd like to access sequentially, but each record itself contains key/value pairs. These arrays tend to be used less frequently than the other homogeneous data structures.
4.7.3.1 Composition of an array of hashes

@LoH = (
    {
       lead     => "fred",
       friend   => "barney",
    },
    {
       lead    => "george",
       wife    => "jane",
       son     => "elroy",
    },
    {
       lead    => "homer",
       wife    => "marge",
       son     => "bart",
    },
  );

4.7.3.2 Generation of an array of hashes

reading from file

format: lead=fred friend=barney

while ( <> ) {
    $rec = {};
    for $field ( split ) {
        ($key, $value) = split /=/, $field;
        $rec->{$key} = $value;
    }
    push @LoH, $rec;
}

reading from file

format: lead=fred friend=barney

no temp

while ( <> ) {
    push @LoH, { split /[\s=]+/ };
}

calling a function that returns a key,value array, like

"lead","fred","daughter","pebbles"

while ( %fields = getnextpairset() ) {
    push @LoH, { %fields };
}

likewise, but using no temp vars

while (<>) {
    push @LoH, { parsepairs($_) };
}

add key/value to an element

$LoH[0]{pet} = "dino";
$LoH[2]{pet} = "santa's little helper";

4.7.3.3 Access and printing of an array of hashes

one element

$LoH[0]{lead} = "fred";

another element

$LoH[1]{lead} =~ s/(\w)/\u$1/;

print the whole thing with refs

for $href ( @LoH ) {
    print "{ ";
    for $role ( keys %$href ) {
         print "$role=$href->{$role} ";
    }
    print "}\n";
}

print the whole thing with indices

for $i ( 0 .. $#LoH ) {
    print "$i is { ";
    for $role ( keys %{ $LoH[$i] } ) {
         print "$role=$LoH[$i]{$role} ";
    }
    print "}\n";
}

print the whole thing one at a time

for $i ( 0 .. $#LoH ) {
    for $role ( keys %{ $LoH[$i] } ) {
         print "element $i $role is $LoH[$i]{$role}\n";
    }
}

</snippet>

Bye
Timothy

--
Zwei Dinge im Leben kannst du nicht zurück holen. Den Pfeil, den du verschossen. Und das Wort, das du gesprochen.
(alte indianische Weisheit)