Hi monks,

In the following code, I'm trying to sort the data according to marks:
use strict; #use warnings; # I'm trying to simulate input from a textfile containing # lines of NameSpaceMarks my @names_marks = ("cliff 76", "john 52", "keith 90", "rob 52"); my (%hash, @names, @marks); foreach (@names_marks) { ($names[$_], $marks[$_]) = split / /, $_; $hash{"$marks[$_]".$names[$_]} = ucfirst($names[$_]). " " . $marks[$ +_]; } foreach my $key (sort {$b <=> $a} keys %hash) { # Prints each value print "\$key: $key \$value: $hash{$key}\n"; } #Output of print $key: 90keith $value: Keith 90 $key: 76cliff $value: Cliff 76 $key: 52rob $value: Rob 52 $key: 52john $value: John 52
I'm able to get the output I expected i.e. the sorted values (Keith 90, followed by Cliff 76 and so on).

The reason I need to append the name to the marks is because I need the hash to contain unique values. But when I do that and with strict warnings on, I get warnings that the element in sort is not numeric. In fact, there are also warnings that the element in the array is not numeric. Can I ignore those warnings?

And how can I improve the code?

I look forward to reading your comments and improvements. Thanks in anticipation.

kiat

In reply to sort hash elements... by kiat

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.