You are most welcome. :) And welcome to the Monastery.

Limbic~Region metioned to me that you might be wanting to preserve the sort, that is, the keys stay sorted even after you add new ones. You can use the CPAN module Tie::Hash::Sorted for this, but first see A Guide to Installing Modules if you are not familiar with the CPAN. Tie's are, in my opinion, a bit hard to grasp if you are new to Perl (see perltie), but here goes anyway. :)

use strict; use warnings; use Data::Dumper; use Tie::Hash::Sorted; my %sequence = ( 1345 => 10, 123 => 20, 500 => 30, ); print Dumper \%sequence; # and here's the part that makes ears bleed ... tie my %sorted_sequence, 'Tie::Hash::Sorted', Hash => \%sequence, Sort_Routine => sub {[sort {$a <=> $b} keys %{$_[0]}]}, ; print Dumper \%sorted_sequence; $sorted_sequence{901} = 40; $sorted_sequence{201} = 50; print Dumper \%sorted_sequence;
Data::Dumper is another CPAN module, but it comes with your Perl installation so you don't have to install it like you do Tie::Hash::Sorted. Once you have \ installed it, run the above example and notice the output. Note that even though your hash stays 'magically' sorted, there are a lot of CPU cycles burned to achieve it. In other words, if you really don't need to keep the hash sorted, then don't don't keep it sorted.

Also, don't rule out using an array. Hashes are really good for quick lookups. If you are more concerned with sorting then looking up items, use an array.

jeffa

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)

In reply to 3Re: sort and hash by jeffa
in thread sort and hash by kaweh

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.