Question

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.

#!/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);
}
Was it helpful?

Solution

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;

OTHER TIPS

Better to err on the side of caution and use an HTML parser to parse 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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top