0

我正在尝试使用 perl 创建哈希表。请可以帮助我,因为我是 perl 的初学者,我正在阅读,但我无法实施。我需要从下面的代码数据编号创建哈希表作为键和描述作为值。

4

1 回答 1

2

对于像 XML 这样的常见数据格式,不要尝试通过逐行读取文件并自己解析来手动执行此操作。相反,请使用 perl 模块为您完成。

XML::Simple模块可能足以让您开始使用。我认为默认情况下该模块已安装在您的系统上。

use strict;   # tip: always use strict and warnings for safety
use warnings;

use Data::Dumper;
use XML::Simple;

my $data = XMLin(\*DATA); # loads up xml into a hash reference assigned to $data
print Dumper $data;       # uses Data::Dumper to print entire data structure to console

# the below section emulates a file, accessed via the special DATA file handle
# but you can replace this with an actual file and pass a filename to XMLin()
__DATA__
<DATA>
    <!-- removed -->
</DATA>

更新

现在 xml 文件已加载到 hashref 中,您可以访问该哈希并将其组织成您想要的结构。

# loads up xml into a hash reference assigned to $data
my $data = XMLin(\*DATA);

# organise into [testnumber => description] mappings
# not sure if 'Detection' is what you meant by 'description'
my %table = ( $data->{Testnumber} => $data->{Detection} );

这个场景的问题是 xml 数据只包含一个测试号,这是所有代码处理的。如果你想处理更多,那么你可能需要在某个地方循环一个数组。我不知道如果有更多xml数据会是什么样子,所以我不知道数组会在哪里。

于 2011-10-03T07:45:38.480 回答