Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

sorting out directories

by kulls (Hermit)
on Jan 07, 2006 at 07:18 UTC ( #521694=perlquestion: print w/ replies, xml ) Need Help??
kulls has asked for the wisdom of the Perl Monks concerning the following question:

Greetings,
I'm reusing the node directory listings in hash and i got a list of directories like ca1, ca2,ca13,ca9,ca4 and so on .
I'll be grateful, if anyone give me a sorted directory list like ca1,ca2...ca9,ca10,ca11 and so on.
Update :
In this directory listings in hash node, i guess they constructing a hash based on each directory. So i need to sort the directories before building a hash.
Can anyone please give me a solution?
-kulls

Comment on sorting out directories
Re: sorting out directories
by saintmike (Vicar) on Jan 07, 2006 at 07:21 UTC
    Use the sort function.
Re: sorting out directories
by Tanktalus (Canon) on Jan 07, 2006 at 07:39 UTC

    Check out the Sort::Naturally module - it should do what you want. Getting the sort function to do this isn't hard, but it's not entirely straight-forward, either. At least not until you see the 'trick' (which is to separate out the letters from the numbers and find a way to sort on them separately - one way is to use an intermediate string where you insert leading zeros - ca1 becomes ca01, for example). And, of course, understand the trick. ;-) Sort::Naturally encapsulates this in a way that makes it easy even for more advanced monks to not get it wrong.

Re: sorting out directories
by sk (Curate) on Jan 07, 2006 at 08:22 UTC
    Tanktalus's suggestion is a better to handle this problem. But if you want something quick and dirty, you can do something like this -

    #!/usr/bin/perl -w use strict; my $base = "ca"; my @dirs = map { $base . int (rand 100) } (1..10); # Instead of matching for $base (ca) you can also match characters etc +. This approach works for simple things and can get complex quickly my @sorted = sort { $a->[0] cmp $b->[0] || $a->[1] <=> $b->[1] } map { [/($base)(\d+)/] } @di +rs; @sorted = map { $_->[0] . $_->[1] } @sorted; print $_, $/ for (@dirs); print $/; print $_, $/ for (@sorted);

    Output

    ca58 ca43 ca98 ca83 ca11 ca59 ca54 ca92 ca69 ca30 ca11 ca30 ca43 ca54 ca58 ca59 ca69 ca83 ca92 ca98
Re: sorting out directories
by planetscape (Canon) on Jan 08, 2006 at 00:56 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://521694]
Approved by monkfan
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (3)
As of 2014-10-25 07:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (142 votes), past polls