Perl hash when both keys and values ​​are array references

I have a problem when pairs of numbers are matched with other pairs of numbers. For example, (1,2) β†’ (12,97). Some pairs can display several other pairs, so I really need the ability to map a pair to a list of lists, for example (1,2) β†’ ((12,97), (4,1)). At the end of the day, I want to separately process each of the values ​​(i.e., each list of lists).

In Python, I could do this by simply saying:

key = ( x, y )
val = [ a, b ]
if (x,y) not in my_dict:
    my_dict[ (x,y) ] = []
my_dict[ (x,y) ].append( [a,b] )

However, in Perl, I have to use refs for keys and values. Therefore, I can say:

$keyref = [ x1, y1 ]
$valref = [ a, b ]
%my_hash = { $keyref => $valref }

But what happens when another pair (x2, y2) arrives? Even if x2 == x1 and y2 == y1, $ keyref = [x2, y2] will be different from the previous generated keyref, so I don’t see a way to do the search. Of course, I could compare (x2, y2) with each dereferenced hash key, but in the end God gave us hash tables to avoid having to do this.

Is there a Perl solution?

Thank,

-W.

+5
source share
3 answers

I ended up using the Socket Puppet solution (in the form of Michael Carmen Option 3). FYI, here is a little Perl script that performs all the operations that I need in my application.

2:, 3: 4:, 5: , , 0: 1: .

, , .

@k1 = ( 12, 13 );
$aref = [ 11, 22 ];
$bref = [ 33, 44 ];
%h = {};
if( not exists $h{$k1[0]}{$k1[1]} ) {
    print "initializing\n";
    $h{$k1[0]}{$k1[1]} = [];
}
push @{$h{$k1[0]}{$k1[1]}}, $aref;
push @{$h{$k1[0]}{$k1[1]}}, $bref;
print "0: ", join ':', @{$h{$k1[0]}{$k1[1]}}, "\n";
print "1: ", join ':', ${$h{$k1[0]}{$k1[1]}}[0], "\n";
print "2: ", join ':', @{${$h{$k1[0]}{$k1[1]}}[0]}, "\n";
print "3: ", join ':', @{${$h{$k1[0]}{$k1[1]}}[1]}, "\n";
print "4: ", join ':', @{$h{$k1[0]}{$k1[1]}->[0]}, "\n";
print "5: ", join ':', @{$h{$k1[0]}{$k1[1]}->[1]}, "\n";

P.S. , , , .

0

Perl - "" . .

"" ?

$hash{$x1}{$y1} = [ $a, $b ];
# or
%hash = ( $x1 => { $y1 => [ $a, $b ] } );


($x2,$y2)=($x1,$y1);
print @{$hash{$x2}{$y2}};   # will print $a and $b
+10

Perl, TMTOWTDI.

1:

$hash{$x,$y} = [$a, $b];

. $;.

Option 2. Use Hash :: MultiKey module

tie %hash, 'Hash::MultiKey';
$hash{[$x, $y]} = [$a, $b];

Option 3. Use HoH (hash hash) instead

$hash{$x}{$y} = [$a, $b];
+2
source

All Articles