Hi there, Me again. The sort function does NOT default to <=>. It defaults to string comparison order. See the Perl doc for sort: "If SUBNAME or BLOCK is omitted, sorts in standard string comparison order. "
So assuming you want numbers sorting, 'sort { $a <=> $b } keys %{$nameref}' would be the way to go. On Sat, Sep 10, 2016, 4:11 PM Jim Gibson <jsgib...@me.com> wrote: > > > On Sep 9, 2016, at 8:54 AM, Nathalie Conte <nco...@ebi.ac.uk> wrote: > > > > Hello, > > I have a question about making a calculation within a loop > > > > I have a hash of hashes > > ############## > > #!/usr/bin/perl > > use strict; > > use warnings; > > > > use Data::Dumper qw(Dumper); > > > > my %grades; > > $grades{"Foo "}{1} = 97; > > $grades{"Foo "}{2} = 107; > > $grades{"Peti "}{1} = 88; > > $grades{"Peti "}{3} = 89; > > $grades{"Peti "}{4} = 99; > > > > print Dumper \%grades; > > print "----------------\n"; > > > > foreach my $name ( keys %grades) { > > foreach my $subject (sort {$a <=> $b} keys %{ $grades{$name} }) { > > print "$name, $subject: $grades{$name}{$subject}\n"; > > } > > } > > > > ############## > > output is > > $VAR1 = { > > 'Peti ' => { > > '4' => 99, > > '1' => 88, > > '3' => 89 > > }, > > 'Foo ' => { > > '1' => 97, > > '2' => 107 > > } > > }; > > ---------------- > > Peti , 1: 88 > > Peti , 3: 89 > > Peti , 4: 99 > > Foo , 1: 97 > > Foo , 2: 107 > > ############### > > Now, what I would like to achieve: > > I want to make a calculation, in each $name (Peti and Foo), calculate: > > for Peti: > > first line : no action > > second line -(minus) 1st line: > > print subject 3-1=2, 89-88=1 > > third line - 2nd line: > > print subject 4-3=1, 99-89=10 > > > > for foo: > > first line : no action > > second line -(minus) 1st line: > > print subject 2-1=2, 107-97=10 > > > > For each $name, declare two variables ($prev_subject and $prev_grade > below) to hold the subject and grade. These variables will be undefined > during the first pass through the inner loop: > > for my $name ( keys %grades ) { > my $nameref = $grades{$name}; # do one hash lookup > my( $prev_subject, $prev_grade ); > for my $subject ( sort keys %{$nameref} ) { # {$a<=>$b} is the default > for sort > my $grade = $nameref->{$subject}; > if( defined $prev_subject ) { > my $subject_delta = $subject = $prev_subject; > my $grade_delta = $grade - $prev_grade; > print "$name: $subject_delta: $grade_delta\n"; > } > $prev_subject = $subject; > $prev_grade = $grade; > } > } > > > > -- > To unsubscribe, e-mail: beginners-unsubscr...@perl.org > For additional commands, e-mail: beginners-h...@perl.org > http://learn.perl.org/ > > >