Đây là lần đầu tiên tôi đã thao tác băm và mảng theo cách này - và nó đang hoạt động. Về cơ bản, cho mỗi khóa có nhiều giá trị mà tôi muốn ghi lại và sau đó in ra dưới dạng "khóa -> giá trị -> giá trị -> val ..."Đây có phải là cách chính xác để xây dựng một hàm băm Perl sử dụng mảng không?
Mã của tôi như sau. Tôi ngạc nhiên rằng nó hoạt động, vì vậy lo ngại rằng nó hoạt động "do nhầm lẫn". Đây có phải là cách chính xác để hoàn thành nhiệm vụ này không, hoặc có phương pháp hiệu quả hơn hay phù hợp hơn không?
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.
}
Bạn thực sự phải ở trong 'sử dụng nghiêm ngặt; sử dụng cảnh báo; 'mode – Zaid
Ouch, đã tạo ra một danh sách cảnh báo độc ác. Tôi sẽ phải trải qua chúng. – Structure
Tôi hy vọng rằng mã thực sự không có nhiều ý kiến này. –