Search code examples
arraysperlloopshashperl-data-structures

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.

#!/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);
}

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;