Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Interchanging hash values

by DrManhattan (Chaplain)
on Apr 19, 2003 at 23:42 UTC ( [id://251738]=note: print w/replies, xml ) Need Help??


in reply to Interchanging hash values

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://251738]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (7)
As of 2024-04-19 15:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found