in reply to Tedious array sort revisited

It seems to me that you want to do this in a perlish way, and that is why you are trying to do it with a foreach loop. However, foreach (@entries) is the wrong type of loop to use for sorting @entries. It can be done, but you're trying to pound a square peg into a round hole. Why? foreach goes through each element of an array, but it doesn't tell you where in the array the elements are located. A sorting routine, by its nature, needs to have at least some information about the location in the array of the elements it's comparing.

          foreach $counter (@entries)

It's a good idea to use correct names for your variables, lest you confuse yourself. The loop variable in a foreach loop is not a counter, unless the array you're iterating over happens to be a counting sequence.

Replies are listed 'Best First'.
Re: Re: Tedious array sort revisited
by gatornek (Initiate) on Feb 05, 2003 at 18:54 UTC
    Thank you for your help. I WAS trying to find a way to use the power of the foreach structure, but you showed me the error of my ways. Would it be better to say something like this:
    for (i = 0, i =< @#entries, i++) { $indexofleast = i; for (j = 1, j =< @#entries, j++) { if (@entries[j] lt @entries[i]) { $indexofleast = j; } if ($indexofleast != i) { $temp = @array[j]; $@array[j] = $@array[i]; $@array[i] = $temp; } } }
    Thanks for anymore help I can get. I stress that I am brand new to perl (so I'm really not sure if I'm using the @# operator correctly). This is supposed to work on single character strings and sort them.

      Close. I think you want $#entries, $array[i] and $array[j].