Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: sorting an array of file names

by Xilman (Friar)
on Dec 19, 2009 at 16:35 UTC ( #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
Node Status?
node history
Node Type: note [id://813533]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (5)
As of 2020-05-27 07:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    If programming languages were movie genres, Perl would be:















    Results (153 votes). Check out past polls.

    Notices?