in reply to Re: Sorting arrays and maintaining an index
in thread Sorting arrays and maintaining an index
This creates the hash and sorts by whatever field is entered on the command line, but that is where I get lost. I don't know how to get to the correct associated fields. Prince99use strict; use vars qw(@Claim_Fields %Claim_Table); my $data_file = "/where/the/file/is"; @Claim_Fields = ( [ 'claim_batch_number', 'N', 'A8' ], [ 'claim_number', 'N', 'A6' ], [ 'claim_type', 'L', 'A2'], [ 'payment_direct', 'N', 'A2'], [ 'pharmacy_number', 'N', 'A6'], [ 'chain_number', 'N', 'A4'], [ 'pharmacy_name', 'L', 'A30'], [ 'reject_code_1', 'N', 'A4'], [ 'reject_code_2', 'N', 'A4'], [ 'rx_number', 'N', 'A8'], ...#many more fields follow); %Claim_Table = get_table(); Main: { my $sort_by = $ARGV[0]; open(CLAIMS, $data_file) or die "CANNOT OPEN FILE: $!"; my @claim_records = (); while (<CLAIMS>) { my $x = $_; while(length($x gt 0)) { $_ = substr($x, 0, 434); $x = substr($x, 434); push(@claim_records, read_record($_)); } } close(CLAIMS); &Sort_File($sort_by, @claim_records); } sub Sort_File { my ($sort_by, @claim_records) = @_; my $sort_sub; # If the sorting type is numeric if ( $Claim_Table{$sort_by} eq 'N' ) { # Create sub for numeric sort $sort_sub = sub { $a->{$sort_by} <=> $b->+ $sort_by} }; } # End if numeric # Otherwise it's lexical else { # Create sub for lexical sort $sort_sub = sub { $a->{$sort_by} cmp $b-> +{$sort_by} }; } foreach my $record ( sort $sort_sub @claim_records ) { print STDOUT $record->{$sort_by}, "\n"; } } sub read_record { my ($line) = @_; my %claim_record = (); @claim_record{ get_fields() } = unpack( get_template(), $line); return \%claim_record; } sub get_fields { my @fields = (); foreach my $claim_field ( @Claim_Fields ) { push(@fields, $claim_field->[0]); } return @fields; } sub get_template { my $template = ''; foreach my $claim_field ( @Claim_Fields ) { $template .= $claim_field->[2]; } return $template; } sub get_table { my %table = (); foreach my $claim_field ( @Claim_Fields ) { $table{$claim_field->[0]} = $claim_field->[1]; } return %table; }
|
|---|