Argh.. painful. Sorry, fellow monk, but that is a very fine example of how not to do it.
- No strict
- No warnings
- Use of & to call a function (unless you can explain to me what it does, and why it was necessary)
- Useless prototype in the function definition
- for(;;) to iterate over an array
- passing results via global variable
Funnily enough, you are already doing the work of "declaring" the variables (using =0; or =();), so you gained nothing by denying yourself the benefits of strict anyway. Why is the second regex in your code so much broader than the first? You end up comparing apples and oranges.. The print "\n.."; style is rather weird as well - not much to make a fuss about, but it just makes the code that bit uglier. And I have to say that, while a matter of taste, there's oodles of meaningless redundancy in your variable names.
Here's a clean version.
#!usr/bin/perl -w
use strict;
sub eat_array {
my $array = shift;
print "The array has " . @$array . " elements\n";
my ($minvalue) = ($array->[0] =~ /\|(\d+)$/);
my ($minidx, $idx) = (0,0);
foreach (@$array) {
my ($currvalue) = (/\|(\d+)$/);
if ($minvalue > $currvalue) {
$minidx = $idx;
$minvalue = $currvalue;
}
++$idx;
}
my $minimum = splice @$array, $minidx, 1;
print "Minimum is: $minimum\n";
return ($minimum, @$array ? eat_array($array) : ());
}
my @testcase = (
'a|a|1', 'a|a|9', 'a|a|0', 'a|a|12',
'a|a|3', 'a|a|4', 'a|a|3', 'a|a|6',
'a|a|9', 'a|a|1', 'a|a|5', 'a|a|7',
'a|a|15', 'a|a|0', 'a|a|8', 'a|a|4',
);
print "\n";
my @results = eat_array(\@testcase);
print @results . " elements.\n@results\n";
All the excercise is for naught though - there already is a built-in sort function. Not only does the old adage about reinventing a wheel apply, but in this of all cases, the existing one is a very good wheel and you need really, really unsual circumstances to justify a reinvention much less one that involves recursion.
Makeshifts last the longest. | [reply] [d/l] [select] |