Fellow monasterians,
I'm trying to refine my Perl skills. I can usually write enough code to make something happen, but without being 'obfuscative' I'd like to write more efficient code.
I'm trying to delete duplicate values in a AoH for later use in HTML::Template. This code does the trick, but maybe a round of golf is needed. I did find this elegant
solution in
Q&A for singling out duplicate values in a straight hash:
my @keys = grep { $hash{$_} eq $value } keys %hash;
but the AoH structure has me a bit confused how this apply. Anyway, here's my code-that-works-but-looks-too-long. Thanks!
#!/usr/bin/perl
use Data::Dumper;
use strict;
my @AoH = ( { page => 'spring' },
{ page => 'winter' },
{ page => 'fall' },
{ page => 'summer' },
{ page => 'spring' }
);
my @allvalues;
for my $i ( 0 .. $#AoH ) {
push ( @allvalues, $AoH[$i]{ page } );
}
my %seen;
my @duplicates = grep { $seen{$_} ++ } @allvalues;
for ( @duplicates ) {
for my $i ( 0 .. $#AoH ) {
if ( $AoH[$i]{ page } eq $_ ){
delete $AoH[$i]{ page };
splice @AoH,$i,1;
last;
}
}
}
print Dumper (@AoH);
—Brad
"A little yeast leavens the whole dough."
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.