【发布时间】:2018-10-26 13:01:45
【问题描述】:
我有一个使用哈希的 Perl 脚本,其中内容是 UUID,键是 XML 文本元素。 XML 文本元素通过普通排序进行合理排序。
在处理每个元素时,我会写入日志文件。相关代码如下所示:
use 5.016;
open(my $loghandle, '>', 'process.log') or die "Couldn't open logfile";
%XMLhash = (
'e01af02f-e8e5-476e-a250-e70c3925463a' => '<Form><AUni ws="fr">retirer</AUni></Form>',
'8187b534-a8c8-4e14-bf0b-1bd9cfada31e' => '<Form><AUni ws="fr">pencher</AUni></Form>',
'1848c7a2-c2f8-4884-8327-c0f1a9da7a4b' => '<Form><AUni ws="en">repair</AUni></Form>',
'b36c127c-91b2-41db-96ec-18c172ad9917' => '<Form><AUni ws="fr">fou</AUni></Form>',
'abb4e9dc-dc66-43b5-951e-e720e21da286' => '<Form><AUni ws="en">four</AUni></Form>',
'8cf707e6-e0a1-4611-bb28-ff18d2de38db' => '<Form><AUni ws="en">robust</AUni></Form>',
);
while( my( $guid, $XMLtext ) = each %XMLhash ) {
my $somestuff = 'What I did', # some process that tells what I did
say $loghandle "Text:$XMLtext Guid:$guid I did $somestuff";
}
以及它产生的日志文件(每次运行的顺序可能不同):
Text:<Form><AUni ws="en">robust</AUni></Form> Guid:8cf707e6-e0a1-4611-bb28-ff18d2de38db I did:What I did
Text:<Form><AUni ws="en">four</AUni></Form> Guid:abb4e9dc-dc66-43b5-951e-e720e21da286 I did:What I did
Text:<Form><AUni ws="fr">retirer</AUni></Form> Guid:e01af02f-e8e5-476e-a250-e70c3925463a I did:What I did
Text:<Form><AUni ws="fr">fou</AUni></Form> Guid:b36c127c-91b2-41db-96ec-18c172ad9917 I did:What I did
Text:<Form><AUni ws="en">repair</AUni></Form> Guid:1848c7a2-c2f8-4884-8327-c0f1a9da7a4b I did:What I did
Text:<Form><AUni ws="fr">pencher</AUni></Form> Guid:8187b534-a8c8-4e14-bf0b-1bd9cfada31e I did:What I did
我希望日志文件按 XML 文本排序,即哈希键。
我尝试将 while 语句更改为:
while( my( $guid, $XMLtext ) = each sort keys %XMLhash ) {
这给了我一个错误:“每个引用的参数类型必须是 unblessed hashref 或 arrayref at ...”
为了有一个排序的日志文件,我可以按键顺序处理哈希吗?
在我当前的解决方法中,我将日志写入一个数组,对该数组进行排序并将该数组写入日志文件。在我看来,这不是最理想的。
【问题讨论】:
-
你说“我希望日志文件按XML文本排序,即哈希的键”。。哈希的键是 UUID; XML 文本是与键关联的值。您可以按值对数据进行排序并以适当的顺序检索键,但这与您所说的 XML 是键不同。