解压chm大家都知道很简单。很多时候用hh来看chm是很痛苦的(比如没有增量查找功能),但是只用hh或者7z解压的chm,根本就没有目录(运气好的话,一些电子书会有目录页),而当我们用hh查看时,.hhc才是真正的目录。。
今天实在觉得不能忍受,于是打开perl写了个将.hhc简单转成.htm的脚本程序,代码最终很简单,但区区花了不少时间去尝试XML::Simple(原以为更简单)。
这段代码后悔没早些写出来,那看chm得轻松很多。^_^
另注:如果你想做的是将chm转换成一个带有hhc目录网页的文件夹,这里 有完整解决方案。
use feature qw(say);
use HTML::TreeBuilder;
if ($#ARGV != 1) {
say "/n/nusage: hhc2idx.pl your.hhc your.htm";
exit;
}
{
my $tree = HTML::TreeBuilder->new; # build empty tree
$tree->parse_file($ARGV[0]); #parse hhc file as HTML
$tree->elementify(); #optional prevent reparse
@objects = $tree->look_down("_tag","object"); #all object
#say "there ar $#objects ob";
for my $ob (@objects) {
my ($el, $dst, $name);
$el = $ob->look_down("name", "Local"); #Local val as <a> href URL
if (defined($el)) {
$dst = $el->attr('value')
}
$el = $ob->look_down("name", "Name"); #Name val as <a> text
if (defined($el)) {
$name = $el->attr('value')
}
#say sprintf('<a href="%s" >%s</a>', $dst, $name);
if (defined($dst) && defined($name)) {
$ob->replace_with(
sprintf('<a href="%s" >%s</a>', $dst, $name)
);
}
}
my $outfile;
open $outfile, ">", $ARGV[1];
say $outfile $tree->as_HTML("", " "); #say out the new html text
# Now that we're done with it, we must destroy it.
$tree = $tree->delete;
}