Greg@Work has asked for the wisdom of the Perl Monks concerning the following question:

I could use a bit of help with my Perl code - specifically, I'm trying to sort a hash... and it does not seem to be cooperating. The hash is built here, comprised of 2 elements - Severity and Note. read in from an xml configuration file, and added to the hash if the uploaded files contain the text the health check is configured to seek out.

my %Relevant; foreach my $e (@{$data->{check}}) { #first go though the health checks looking to see if we have r +elevant checks for this event code if ($e->{relevant_events} =~ $FindEvent ) { $WantedFile = $e->{filename}; $WantedText = $e->{find}; #scan the files for the text we are after DXWanted(); if ($FileStatus == 1) { $Relevant{$e->{severity}} = $e->{note}; $FileStatus = 0; } }

Later in the code, I want to sort the hash descending by the numerical value of severity:

foreach my $name (sort { $Relevant{$b} <=> $Relevant{$a} } keys %Relev +ant) { $RESULTS = $RESULTS . "Severity: " . $name . "\n" . $Relevant{ +$name} . "\n\n" }

Can anyone spot what I've done wrong? Thanks very very much,

Replies are listed 'Best First'.
Re: My Perl-foo... SORT is not strong
by Anonymous Monk on Mar 19, 2015 at 14:55 UTC

    You're sorting by $Relevant{$key}, which you've populated with $e->{note}. Try a plain sort { $b <=> $a } keys %Relevant maybe?

      Thank you for your quick reply. I'm horribly new to Perl and it's nice to have someone looking over my shoulder. I made the change you suggested and sadly am getting an error - probably since I didn't show you all the code....

      #all the checks have been run - now sort the 2 hashes, and print out t +heir contents to the note. my $ReleventCount = scalar keys %Relevent; if ($ReleventCount >= 1) { foreach my $name (sort { $b <=> $a } keys %Relevant) { $RESULTS = $RESULTS . "Severity: " . $name . "\n" . $Relevent{ +$name} . "\n\n" } }

      Error: Global symbol "%Relevant" requires explicit package name at PSFT_Automation.pl line 641. Execution of PSFT_Automation.pl aborted due to compilation errors. Again, Thanks for helping me out

        Note the spelling: "Relevant" is not "Relevent".