简体   繁体   English

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

[英]How do I pass all elements of “array of hashes” into function as an array

How do I pass a element of "array of hashes" into function as an array? 如何将“哈希数组”元素作为数组传递给函数?

say for instance I wanted to pass all $link->{text} as an array into the sort() function. 比方说,我想将所有$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);
}

If you want to sort your links by text, 如果要按文本对链接进行排序,

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

If you actually just want to get and sort the text, 如果你真的只想获取和排序文本,

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

Better to err on the side of caution and use an HTML parser to parse HTML: 最好小心谨慎并使用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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM