Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations dencom on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

sorting an array 1

Status
Not open for further replies.

jriggs420

Programmer
Sep 30, 2005
116
US
I have this code
Code:
      3 @alpha=("Names","Steve","Linus","Larry","Bill");
      4 @alpha=sort(@alpha);
      5         foreach $name (@alpha){print $name."\n";}
      6 #print @alpha;
Suppose I only wanted to sort $alpha 1-4 (every line but the first one), how would I go about this? I'm looking for in general type solution here. Also the number of 'names' in the array will be dynamic. TIA

Joe

A clever person solves a problem.
A wise person avoids it.

-- Einstein
 
Cool thanks again Ishnid. What if the array contains more than five items tho? That's really the part that's giving me the most trouble. Here's the best code I have come with now:
Code:
      3 @alpha=("Names","Steve","Linus","Larry","Bill");
      4 $first=shift(@alpha);
      5 @alpha=sort(@alpha);
      6 unshift(@alpha, $first);
Of course your code looks more efficient. But I can't figure out the syntax to get yours working. Seems like it would be
Code:
@alpha[1..$#] = sort @alpha[1..$#];
perl doesn't like that line tho, something about a referenced variable I think. Do you have any ideas about this?

A clever person solves a problem.
A wise person avoids it.

-- Einstein
 
You probably should be using a more suitable data structure:

my $names = { NAMES => [qw(Fred Jane Jim Sally)] };
my $names = [qw(Fred Jane Jim Sally)];
etc
etc

or even just a regular old hash:

%names = (
Sally => 1,
Fred => 1,
Jane => 1,
Jim => 1
);

where the number 1 could be some related info about each person/name.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top