本篇我们会看到 Perl 成为知名编程语言的关键特色--哈希 hash(2000年以前叫:关联数组)。
在Perl 中,可以使用各种模块和函数来解析 XML元素和属性。其中,最古老的模块是 XML::Parser,它提供了一组完整的XML解析和处理函数,可以解析XML文档中的元素和属性。
例如,下面是一个使用 XML::Parser 模块解析 XML元素和属性 的示例代码:
编写 xml_parser_subs.pl 如下
#!/usr/bin/perl -w
use 5.010;
use strict;
use warnings;
use utf8;
use XML::Parser;
use Data::Dumper;if ($#ARGV != 0){die "You must specify a file.xml to parse";
}
my $file = shift @ARGV;
# Tree 风格比较难用,它的数据结构不是标准的JSON.
my $p1 = XML::Parser->new(Style => 'Tree');
my $tree = $p1->parsefile($file) or die "cannot read file.xml\n";
#print Dumper($tree);# Subs 风格比较容易使用,它需要对应于标签名定义子程序
my $p2 = XML::Parser->new(Style => 'Subs',Handlers => {Char => \&text});
my $doc = $p2->parsefile($file) or die "cannot read file.xml\n";
say '$doc is a ', $doc;my $f2 = $file .'.txt';
# 写入文件
open(my $fw, '>:encoding(UTF-8)', $f2) or die "cannot open file '$f2' $!";
my @array;
# 访问 hash
sub node { my ($self, $tag, %attribs) = @_;push @array, $attribs{'TEXT'};
}
sub node_ {my ($self, $tag) = @_;
}
sub text {my ($self, $text) = @_;
}
my $ln =0; # 行数
foreach my $txt (@array){print $fw $txt ."\n";$ln++;
}
close($fw);
print $ln;
运行 perl xml_parser_subs.pl your_test.xml