I have noticed that more and more people are trying to apply perl solutions to problems by regurgitating code that solves but doesn't completely apply to the problem trying to be solved. There are alot of people learning perl who have all the required books, but bite off more they can chew. If people would break the overall problem into tiny little ones, most of the syntax problems you could have are solved for you in one of the books. Then your big problem just becomes a matter of applying correct programming theory, and some streamlining.
Case in point:
I am still new enough to perl that I live with the perl books, and I was looking for a way to specifically sort a list, and keep duplicates out at the same time in a minimal number of passes. I don't know if the solution I eventually came up with was the most efficient one possible, but it beat the hell out of my first attempt. For demonstration purposes I modified my solution to make it a bit weirder then what I needed. But I Basically took my problem and broke it into three steps, 1) How does one efficiently sort on multiple criteria? 2) How does one efficiently handle duplicates? 3) How do I combine the previous steps into an applicable solution?
This little snippit comes from combining lesson 4.6 and 4.15 in the perl cookbook. It takes a list and sorts it by ascending length, descending character value, and then removes the dupes
#! /usr/bin/perl
use strict;
my @unsorted =
("A","B","C",9,"B","B","AAA","D",4,"EE","BBB",55,"BBBB","CCC",55,"BBDB
+","BBB","JJ","ZZZZZZ","A blue flamingo doesn't have spots");
my %listed=();
my @sorted = grep { ! $listed{$_} ++}
map { $_->[1] }
sort { $a->[0] <=> $b->[0]
||
$b->[1] cmp $a->[1] }
map { [ length $_, $_ ] }
@unsorted;
for(@sorted){
print "$_\n";
}
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.