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 Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Multiple Columns Sorting / Array 1

Status
Not open for further replies.

Extension

Programmer
Joined
Nov 3, 2004
Messages
311
Location
CA
Hi,

I'm trying to sort sort a multiple columns flat file converted to arrays but I must be doing something wrong. (stupid error)
See my data structure (file) and code below:

Code:
ID|NAME|ADDRESS|SOMETHING|
11|Ben|223 Long Street|Some Data

Code:
	open(TBL,"$Filename") || die("Can't open flat file");
		my $ColumnNames = <TBL>;
		my @Table = <TBL>;
	close(TBL);
			
  				foreach my $record (sort { $a->[1] cmp $b->[1] } @Table) {	
				chomp $record;
       
 					my @Field=split(/\|/,$record);
				
				if ($Field[1] ne 0) {
				 print qq ( $Field[1] \n );
				}
			}
 
You're just reading the lines in from the text file as strings, you're not breaking them into arrays prior to the sort. Take a look at the perldocs perlreftut, perldsc and perllol for information on references and data structures.

In the mean time, see if this helps:
Code:
my (@headers, @table);
@headers = split(/\|/, scalar <DATA>);
chomp @headers;

@table = map {chomp; [split /\|/, $_]} <DATA>;

print join('_', @headers), "\n";

foreach (sort {	$a->[1] cmp $b->[1] ||
		$a->[0] <=> $b->[0]   } @table) {
    print join('_', @{$_}), "\n";
}

__DATA__
ID|NAME|ADDRESS|SOMETHING|
11|Ben|223 Long Street|Some Data
30|Joe|4321 Second Ave.|Comments
20|Mike|1000 First St.|Comments
31|Joe|1234 Tenth Ave.|Another Joe
12|Bob|123 Main St.|Comments
When you're reading in the lines from the text file, you'll probably want to make sure they contain good data prior to adding them to the array, but this should give you a place to start.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top