CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate: Re: [jkepler] Sorting an hash array: Edit Log



Laurent_R
Veteran / Moderator

Jul 26, 2014, 4:35 AM


Views: 5600
Re: [jkepler] Sorting an hash array

Hi,

The single most important problem is that, in this line:


Code
print out "Key: $_ and Value: $functions{$_}\n" foreach (keys%functions);

you are not using the result of your sort, which is stored in the @keys array.

It should presumably be:

Code
print out "Key: $_ and Value: $functions{$_}\n" foreach @keys;


You did not say what the content of your %functions hash is, so using the <=> operator may or may not be right, depending on which type of sort you want (<=> is for sorting data numerically). If you really need alphatetical sort, then use the cmp function instead of <=>.

Your close statement is not doing anything useful since you don't pass it the filehandle. And BTW, you should rather use lexical filehandles and the 3-argument syntax for open, and also check the result of the open statement. Something like this:


Code
my $info = "out.txt";  
open my $out, ">", $info or die "Could not open $info $! ";
print $out "Key: $_ and Value: $functions{$_}\n" for @keys;
close $out;


As a final point, I would add that this line:

Code
my @vals = @functions{@keys};

isn't doing anything useful either, since you are never using @vals.

PS: Some of the errors above might have been detected by the compiler if you had used the following pragmas:

Code
use strict; 
use warnings;

which you should include in every single piece of code having more than 1 line that you write.


(This post was edited by Laurent_R on Jul 26, 2014, 4:42 AM)


Edit Log:
Post edited by Laurent_R (Veteran) on Jul 26, 2014, 4:37 AM
Post edited by Laurent_R (Veteran) on Jul 26, 2014, 4:40 AM
Post edited by Laurent_R (Veteran) on Jul 26, 2014, 4:42 AM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives