There are a couple of ways you can improve on this. First, you can access the last element of an array by using the index -1. I.e.
$sort[scalar @sort - 1] == $sort[-1];
Also, you can swap the values of two variables without a temporary variable in the middle:
($a, $b) = ($b, $a); # swap the values of $a and $b
So your code can be rewritten like so:
#!/usr/bin/perl -w
use strict;
use Data::Dumper;
my %hash = (Matt => 24,
Dana => 19,
Eric => 28,
Sara => 20,
John => 17,
Mike => 23,);
print Dumper \%hash;
my @sort = sort {$hash{$a} <=> $hash{$b}} keys %hash;
($hash{$sort[0]}, $hash{$sort[-1]})
= ($hash{$sort[-1]}, $hash{$sort[0]});
print Dumper \%hash;
-Matt
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.