While writing
this (shameless plug), i came up with a (almost) one-line way of removing duplicates from an ever-expanding array and sorting the remaining values. Unfortunately i have two problems:
1) Me thinks this isn't the best way to do it (i really don't want to create two hashes)
2) i don't understand completely why it works.
So, if monks with better knowledge of grep could please help me out here, i would much appreciate it.
sub beautify {
my (%old, %new);
return sort { $a <=> $b }
grep {
$new{$_}++;
$old{$_}++ unless exists $old{$_};
my $ret = $new{$_}==$old{$_} ?
1 :
$new{$_}+1==$old{$_} ? 1 : 0;
$old{$_} = $new{$_};
$ret;
} @_;
}
This gets as called as
@array = beautify(@array, $new_value, $new2);
What i want to know is, why doesn't grep just return all values as being ok (since it looks like $old{$_} will always be within 1 of $new{$_})?
And what better ways are there to do this (in one line)?
Please help,
jynx
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.