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

时间:2010-12-15 23:23:04

标签: arrays perl loops hash perl-data-structures

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

例如,我想将所有$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);
}

2 个答案:

答案 0 :(得分:6)

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

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

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

my @text = sort map $_->{text}, @array_of_links;

答案 1 :(得分: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;