E
Estella
Hello, I just learnt Perl scripting, and I have been trying to do this
hw assignment, and I got so stuck in sorting a file with the key that
is calculated using the fields in the file. Here is what I have to do:
There is a file that contains county name, population size, water area
(in square miles), land area (in square miles).
Adams County 16428 4.73 1924.96
Asotin County 20551 5.34 635.34
Benton County 142475 57.03 1703.09
Chelan County 66616 72.25 2921.37
Clallam County 64525 930.89 1739.45
Clark County 345238 27.99 628.22
....
So we need to calculate the population density and water percentage,
and then print out the ascending order of the population density, and
also ascending order of the water percentage.
I did something like this, but I couldn't sort the list.
#!/net/local/bin/perl
while (<>) {
my($aa, $bb, $cc, $dd) = /^(\w+.+)\t(\d+)\t(\d+.\d+)\t(\d+.\d+)/ or
(warn "bad format on line $.:$_"), next;
$popden = $bb/$dd;
$waterpec = ($cc/($cc+$dd))*100;
printf("%s %d %.2f%%\n", $aa, $popden, $waterpec);
#open FH, ">> $tmp" or die $!;
}
foreach (sort keys %popden) {
printf("%s %.2f %.2f%%\n", $aa, $popden, $waterpec);
}
I tried to look at a lot of sort examples online, but I am still
lost...is that something wrong with my logic? or I have to do
something more, like writing the list to a file first and then sort it
again..or..I dunno.
Thanks for helping...
hw assignment, and I got so stuck in sorting a file with the key that
is calculated using the fields in the file. Here is what I have to do:
There is a file that contains county name, population size, water area
(in square miles), land area (in square miles).
Adams County 16428 4.73 1924.96
Asotin County 20551 5.34 635.34
Benton County 142475 57.03 1703.09
Chelan County 66616 72.25 2921.37
Clallam County 64525 930.89 1739.45
Clark County 345238 27.99 628.22
....
So we need to calculate the population density and water percentage,
and then print out the ascending order of the population density, and
also ascending order of the water percentage.
I did something like this, but I couldn't sort the list.
#!/net/local/bin/perl
while (<>) {
my($aa, $bb, $cc, $dd) = /^(\w+.+)\t(\d+)\t(\d+.\d+)\t(\d+.\d+)/ or
(warn "bad format on line $.:$_"), next;
$popden = $bb/$dd;
$waterpec = ($cc/($cc+$dd))*100;
printf("%s %d %.2f%%\n", $aa, $popden, $waterpec);
#open FH, ">> $tmp" or die $!;
}
foreach (sort keys %popden) {
printf("%s %.2f %.2f%%\n", $aa, $popden, $waterpec);
}
I tried to look at a lot of sort examples online, but I am still
lost...is that something wrong with my logic? or I have to do
something more, like writing the list to a file first and then sort it
again..or..I dunno.
Thanks for helping...