in reply to Better way to do this, regex etc.
Here's my rewrite:
I started with your same test, and ended by ensuring that the sorted output matched what you had before. So, it at least passes this test. Just some quick notes... I drastically changed your regex. Instead of matching multiple commas between numbers, I now only match digits-(spaces?-one_comma-spaces?-digits)*. So, "123, 456" is good, "123,,456" is discarded.#!/usr/bin/perl -w use strict; use warnings; use Sort::Key qw(usort); use List::MoreUtils qw(uniq); my $bug_fix_msg = "this 33,44 is a fix for mybug44,99 real \ bug 99 again bug33r bug1722,3 bUg:99, \ bugs:456, 17, 24 bugs 42,58 bug: 50,50"; my @bug_array = map { split /\s*,\s*/, $_ } $bug_fix_msg =~ m/\bbugs?\s*:?\s*(\d+(?:\s*,\s*\d+)*)\b/ig; my @sorted = usort uniq @bug_array; print "\n sorted: @sorted\n"; print "OK!\n" if "@sorted" eq "3 17 24 42 50 58 99 456 1722";
Then I split each of the regex matches, and the split is that space-comma-space section. This gets rid of the spaces at the same time as doing the split, which makes it a bit less work to read/understand/execute.
Then the unique/sorting steps, I went to modules. List::MoreUtils is one of my favourite modules for useful tidbits of code where I don't have to worry about bugs. It's often faster than a hand-written version due to being XS, but it's always faster in developer time, once you're familiar with them. I don't have to think about it - I just call "uniq LIST". And then, rather than doing $a vs $b comparisons, I know that Sort::Key, which is also mostly native XS code, already does this. This shouldn't be much different than your version, but can be a tiny bit more explicit. Sort::Key has many other options for sorting, too, so you may want to get familiar with it anyway.
Hope that helps.
Update: Thank you for a) posting your code, b) describing what you wanted to do, and c) providing a built-in test that others could use to get a better idea of what you're talking about. Oh, and d) providing a negative test ("bug33r"). All VERY helpful. I wish I could give a ++ for each of these points.
|
|---|