2

如何将“哈希数组”的元素作为数组传递给函数?

例如,我想将 all$link->{text}作为数组传递给sort()函数。

#!/usr/bin/perl
use strict; use warnings;

my $field = <<EOS;
<a href="baboon.html">Baboon</a>
<a href="antelope.html">Antelope</a>
<a href="dog.html">dog</a>
<a href="cat.html">cat</a>
EOS

#/ this comment is to unconfuse the SO syntax highlighter. 
my @array_of_links;
while ($field =~ m{<a.*?href="(.*?)".*?>(.*?)</a>}g) {
    push @array_of_links, { url => $1, text => $2 };
}
for my $link (@array_of_links) {
    print qq("$link->{text}" goes to -> "$link->{url}"\n);
}
4

2 回答 2

6

如果您想按文本对链接进行排序,

my @sorted_links = sort { $a->{text} cmp $b->{text} } @array_of_links;

如果您实际上只是想获取文本并对其进行排序,

my @text = sort map $_->{text}, @array_of_links;
于 2010-12-15T23:29:51.557 回答
3

最好谨慎行事并使用 HTML 解析器来解析 HTML:

use strict; use warnings;

use HTML::TokeParser::Simple;

my $field = <<EOS;
<a href="baboon.html">Baboon</a>
<a href="antelope.html">Antelope</a>
<a href="dog.html">dog</a>
<a href="cat.html">cat</a>
EOS

my $parser = HTML::TokeParser::Simple->new(string => $field);

my @urls;

while ( my $tag = $parser->get_tag ) {
    next unless $tag->is_start_tag('a');
    next unless defined(my $url = $tag->get_attr('href'));
    my $text = $parser->get_text('/a');
    push @urls, { url => $url, text => $text };
}

@urls = sort {
    $a->{text} cmp $b->{text} ||
    $a->{url}  cmp $b->{url}
} @urls;

use YAML;
print Dump \@urls;
于 2010-12-16T00:51:37.100 回答