Esta es la primera vez que manipulo hashes y matrices de esta manera, y está funcionando. Básicamente, para cada clave hay múltiples valores que quiero registrar y luego imprimir en la forma "clave -> valor -> valor -> val ..."¿Es esta la forma correcta de crear un hash Perl que utiliza matrices?
Mi código es el siguiente. Me sorprende que funcione, tan preocupado que funciona "por error". ¿Es esta la manera correcta de realizar esta tarea, o hay un método más eficiente o apropiado?
while ($source =~ m/(regex)/g) { #Get all key names from source
$listkey = $1; #Set current list key to the current regex result.
$list{$listkey} = ++$i unless $list{$listkey}; #Add the key to the hash unless it already exists.
$list{$listkey} = [] unless exists $list{$listkey}; #Add an array for the hash unless the hash already exists.
while ($loopcount==0) {
if ($ifcount==0) {
$listvalue=result_of_some_function_using_list_key; #Get the first list value by using the list key.
$ifcount++; #Increment so we only get the first list value once.
} else {
$listvalue=result_of_some_function_using_list_value; #Update the list value by using the last list value.
}
if ($listvalue) { #If the function returned a value...
push @{$list{$listkey}}, $listvalue; #...then add the value to the hash array for the key.
} else { #There are no more values and we need a new key.
$listkey=0; #Reset variable.
$listvalue=0; #Reset variable.
$loopcount++; #Increment loop counter to exit loop.
}
}
$ifcount=0; #Reset count variable so the next listvalue can be generated from the new key.
$loopcount=0; #Reset count variable so another loop can begin for a new key.
}
foreach $listkey (keys %list) { #For each key in the hash.
print "$listkey --> "; #Print the key.
@values = @{$list{$listkey}}; #Reference the arrays of the hash.
print join ' --> ', @values; #Print the values.
print "\n"; #Print new line.
}
Realmente debería estar en 'use strict; utilizar advertencias; 'modo – Zaid
Ouch, que produjo una lista malvada de advertencias. Tendré que pasar por ellos. – Structure
Espero que el código real no tenga tantos comentarios. –