/ / Jak zbudować strukturę danych hash - perl, hashtable

Jak zbudować strukturę danych hash - perl, hashtable

Mam problem z ustaleniem, jak utworzyć kilka %th2 struktury (patrz poniżej), z których każda będzie wartością $th1{0}, $th1{1}, i tak dalej.

Próbuję też dowiedzieć się, jak przechodzić przez klawisze w drugim skrócie %th2. Wchodzę w ten błąd, który jest często omawiany w SO,

Can"t use string ("1") as a HASH ref while "strict refs" in use

Również, gdy przypiszę %th2 do każdego klawisza %th1, Zakładam, że jest to skopiowane %th1 jako anonimowy hash i że nie nadpisuję tych wartości w miarę ich ponownego użycia %th2.

use strict;

my %th1 = ();
my %th2 = ();
my $idx = 0;

$th2{"suffix"} = "A";
$th2{"status"} = 0;
$th2{"consumption"} = 42;

$th1{$idx} = %th2;

$idx++;

$th2{"suffix"} = "B";
$th2{"status"} = 0;
$th2{"consumption"} = 105;

$th1{$idx} = %th2;

for my $key1 (keys %th1)
{
print $key1."nn";
for my $key2 (keys %$key1)
{
print $key2->{"status"};
}

#performing another for my $key2 won"t work. I get the strict ref error.
}

Odpowiedzi:

4 dla odpowiedzi № 1

Zmiana:

$th1{$idx} = %th2;

do:

$th1{$idx} = %th2;

Następnie możesz utworzyć pętlę jako:

for my $key1 (keys %th1) {
for my $key2 (keys %{$th1{$key1}} ) {
print( "Key1=$key1, Key2=$key2, value=" . $th1{$key1}->{$key2} . "n" );
}
}

Lub .. bardziej wyraźnie:

for my $key1 (keys %th1) {
my $inner_hash_ref = $th1{$key1};

for my $key2 (keys %{$inner_hash_ref}) {
print( "Key1=$key1, Key2=$key2, value=" . $inner_hash_ref->{$key2} . "n" );
}
}

1 dla odpowiedzi nr 2
  1. $th1{$idx} = %th2;
    

    powinno być

    $th1{$idx} = %th2;
    

    W hashu mogą być przechowywane tylko skalary, więc chcesz zapisać odniesienie do %th2. (%th2 w kontekście skalarnym zwraca dziwny ciąg zawierający informacje o elementach wewnętrznych mieszania.)

  2. keys %$key1
    

    powinno być

    keys %{ $th1{$key1} }
    

    $key1 jest łańcuchem, a nie odniesieniem do skrótu.

  3. $key2->{"status"}
    

    powinno być

    $th1{$key1}{$key2}{"status"}
    

    $key2 jest łańcuchem, a nie odniesieniem do skrótu.