Это первый раз, когда я манипулировал хэшами и массивами таким образом - и он работает. В принципе, для каждого ключа есть несколько значений, которые я хочу записать, а затем распечатать в форме «key-> value -> value -> val ...»Это правильный способ создания хэша Perl, который использует массивы?
Мой код выглядит следующим образом. Я удивлен, что он работает, поэтому он обеспокоен тем, что он работает «по ошибке». Является ли это правильным способом выполнения этой задачи или существует более эффективный или подходящий метод?
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.
}
Вы действительно должны быть в 'use strict; использовать предупреждения; 'mode – Zaid
Ой, это вызвало злой список предупреждений. Мне придется пройти через них. – Structure
Я надеюсь, что настоящий код не содержит много комментариев. –