2010-03-25 13 views
5

Come creare un riferimento al valore in una chiave hash specifica. Ho provato quanto segue ma $$ foo è vuoto. Ogni aiuto è molto apprezzato.Come posso prendere un riferimento a un valore hash specifico in Perl?

$hash->{1} = "one"; 
$hash->{2} = "two"; 
$hash->{3} = "three"; 

$foo = \${$hash->{1}}; 
$hash->{1} = "ONE"; 

#I want "MONEY: ONE"; 
print "MONEY: $$foo\n"; 
+0

Se le tue chiavi di hash sono tutti interi positivi, probabilmente dovresti usare un array. – daotoad

risposta

5

Attiva severi e avvisi e otterrai alcuni indizi su cosa non va.

use strict; 
use warnings; 

my $hash = { a => 1, b => 2, c => 3 }; 
my $a = \$$hash{a}; 
my $b = \$hash->{b}; 

print "$$a $$b\n"; 

In generale, se si vuole fare le cose con le fette o prendendo refs , hai avuto modo di utilizzare il vecchio stile, accatastato sintassi sigillo per ottenere quello che vuoi. È possibile trovare lo References Quick Reference a portata di mano, se non si richiamano i dettagli della sintassi del sigillo accatastato.

aggiornamento

Come murugaperumal punti fuori, si può fare my $foo = \$hash->{a}; Potrei giurare ho provato e che non ha funzionato (con mia grande sorpresa). Lo afferro per la stanchezza rendendomi più stupido.

8
use strict; 
use warnings; 
my $hash; 

$hash->{1} = "one"; 
$hash->{2} = "two"; 
$hash->{3} = "three"; 

my $foo = \$hash->{1}; 
$hash->{1} = "ONE"; 
print "MONEY: $$foo\n"; 
Problemi correlati