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

print the first and the last element of an hash 1

Status
Not open for further replies.

Jurafsky

Programmer
Oct 27, 2012
11
0
0
IT
Hello all! I've a csv file like :


City sunshine Temperature
Ajaccio 2790 14.7
Lyon 2072 11.4
Marseille 2763 14.2
Brest 1729 10.8
Lille 1574 9.7
Paris 1833 11.2
Strasbourg 1685 9.7

I'd like to print just the city+temperature with the highest and the lowest temperature. How?

Perl:
#!/usr/bin/perl
use warnings;
use diagnostics;
use Data::Dumper;
$Data::Dumper::Terse = 1;
$Data::Dumper::Indent = 0;
 

#definyn arrays for temperatures, files and city
my (@temp, @file, @ville);
my ($file, $line);
my %temperature;

$file = "temperatures.csv";
#I don't consider the first line of the file and I put just the city and  its temperture in two arrays

open (F, "<", $file);
while(defined($line = <F>)) {
if ( $. > 1 ) {
	@file = split(/ /, $line);
	push(@ville, $file[0]);
	push(@temp, $file[2]);
	}
}

#then I create the hash and print what  there's inside

@temperature{@ville} = @temp;
print '%temperature : ', Dumper(\%temperature), "\n";

#now I "order" the hash by value 
foreach my $value (sort {$temperature{$a} <=> $temperature{$b} || ($a cmp $b) } keys %temperature) 
{
     print " the city of $value and its temperature : $temperature{$value}\n";
}


close(F);

#is there a way to print ONLY the first and the last element in order to have the highest and the lowest temperature?
 
If you need the hash for other purposes
Code:
my@tord;
@tord=sort{$temperature{$a}<=>$temperature{$b}}keys%temperature;
print 'The city of $tord[0] and its minimum temperature : ',$temperature{$tord[0]},"\n";
print 'The city of $tord[-1] and its maximum temperature : ',$temperature{$tord[-1]},"\n";
otherwise
Code:
my($maxt,$mint,$temp,$maxv,$minv,$ville)=(-1e300,1e300);
open(F,$file);
$line=<F>;
while(<F>){
  ($ville,undef,$temp)=split;
  if($temp>$maxt){
    $maxt=$temp;
    $maxv=$ville;
  }
  if($temp<$mint){
    $mint=$temp;
    $minv=$ville;
  }
}
print 'The city of $minv and its minimum temperature : ',$mint,"\n";
print 'The city of $maxv and its maximum temperature : ',$maxt,"\n";

Franco
: Online engineering calculations
: Magnetic brakes for fun rides
: Air bearing pads
 
Thank you (Grazie!),

I found this

Perl:
$regex .= $t9{$num};

in an exercice. What is ".=" and how is it called? This is the first time I've seen it.
 
Thank you! now is clear!

$regex .=$t9{$t};

it's the same as...

$regex = $regex.$t9{$t}; !
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top