Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Sorting - lower to upper

by Joost (Canon)
on Jul 15, 2004 at 15:45 UTC ( [id://374695]=note: print w/replies, xml ) Need Help??


in reply to Sorting - lower to upper

A hash is inherently unsorted. You can sort a list of keys and store them in an array, though:
my @keys = sort keys %hash; # adapt to your needs here. for (@keys) { print "$_ => $hash{$_}\n"; }
edit: %hash{$_} -> $hash{$_}

edit2: This seems to me reasonably efficient:

my @keys = map { tr/a-zA-Z/A-Za-z/; $_ } sort map { tr/a-zA-Z/A-Za-z/; + $_ } keys %hash;

Replies are listed 'Best First'.
•Re^2: Sorting - lower to upper
by merlyn (Sage) on Jul 15, 2004 at 16:45 UTC
    ... map { tr/a-zA-Z/A-Za-z/; $_ } ...
    I'm always a bit wary of code that looks like that, especially when it doesn't have the big warning sign to the right that says:
    Warning
    This map alters its incoming arguments as well as generating the desired list. While it is safe in this particular usage, use caution when copying this to another segment of code.

    In other words, I'd have written that as:

    ... map { (my $x = $_) =~ tr/a-zA-Z/A-Za-z/; $x } ...
    which ensures that I get the desired output value without seriously mangling my input value as a side-effect.

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (2)
As of 2024-04-24 18:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found