Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: sorting an array of file names

by Xilman (Hermit)
on Dec 19, 2009 at 16:35 UTC ( [id://813533]=note: print w/replies, xml ) Need Help??


in reply to sorting an array of file names

I suggest you read up on the sort() function, whether chewed trees in the Camel book or with "perldoc -f sort".

sort() can be given a function to define the sorting order. Your specification, "sort these files with respect to their first digit" is somewhat ambiguous. What do you want to do if two files have the same first digit? What do you want to happen if the file doesn't have a first digit?

If I assume that you don't care what happens when a file doesn't contain a digit and when two files contain the same first digit, something like this might be what you require:

sub mysort() { my ($a_digit) = ($a =~ /(\d)/); my ($b_digit) = ($b =~ /(\d)/); return 1 unless defined $a_digit && defined $b_digit; return $a_digit <==> $b_digit; } # Code to put file names into @files sort mysort @files;

Paul

Log In?
Username:
Password:

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

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

    No recent polls found