#!/usr/bin/perl;
use strict;
use warnings;
use Data::Dumper;
my $n = 3;#Decided position
my $filename = 'sample file.txt';
open my $fh, '<', $filename or die "Failed to open $filename: $!";
while (<$fh>){
next if m/^#/;#Skip comment lines
my @array = ();
foreach (1 .. $n){
my $rec = <$fh>;
last unless defined $rec;
$rec =~ s/\s*$//;#Remove spaces or newline characters from end
push @array, $rec;
}
@array = sort {my ($sa) = split /\s+/, $a;
my ($sb) = split /\s+/, $b;
$sb <=> $sa;} @array;
my $label = "decided position $n";
foreach(@array){
printf "%-23s%s\n", ($label, $_);
$label = '';
}
}
#!/usr/bin/perl;
use strict;
use warnings;
my $n = 3;#Decided position
my $line_count = 0;
my $filename = 'sample file.txt';
open my $fh, '<', $filename or die "Failed to open $filename: $!";
LINE: while (1){
my %hash = ();
foreach (1 .. $n){
my $rec = <$fh>;
last LINE unless defined $rec;
$rec = <$fh> while $rec =~ m/^#/;#Skip comment lines
$rec =~ s/\s*$//;#Remove spaces or newline characters from end
$hash{++$line_count} = $rec;
}
my @array = sort {my ($sa) = split /\s+/, $hash{$a};
my ($sb) = split /\s+/, $hash{$b};
$sb <=> $sa;} keys(%hash);
my $label = "decided position $line_count\n";
foreach(@array){
print $label;
printf "%15d%10s\n", ($_, $hash{$_});
$label = '';
}
}
Thank d5e5 very much.
I can study a lot of from your script.
Could you show how to use the script if n = lenght of data.
Sorry, I only know how to write the script for a pre-determined value of n. It looks like $n represents the number of data lines to read before sorting and I don't know how to determine the length of data before reading them.