Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any guarantee that results of globbing will be sorted in Perl?

Tags:

sorting

glob

perl

Is there any guarantee that the array of filenames returned from a glob (e.g. <*>) will be sorted?

I can't find that sorting is mentioned one way or the other in the documentation, but it seems to be the case in every directory I've tried it on.

I'm talking about using this syntax:

@files = <*>;

If I need the files to be sorted, would the below be redundant?

@files = sort(<*>);
like image 611
Kip Avatar asked Sep 22 '09 17:09

Kip


1 Answers

In Perl 5.6.0 and newer, filenames are sorted:

Beginning with v5.6.0, this operator is implemented using the standard File::Glob extension.

-- perldoc for glob

By default, the pathnames are sorted in ascending ASCII order.

-- perldoc for File::Glob

There is one catch:

By default, file names are assumed to be case sensitive

-- perldoc for File::Glob

Having said all that, you can change this behavior to sort case-insensitively with

use File::Glob qw(:globally :nocase);

Note that :globally is redundant since 5.6.0, but this will work on older versions as well.

Alternately, if you just want to do a single glob with case-insensitivity:

use File::Glob ':glob';

@files = bsd_glob('*', GLOB_NOCASE);
like image 114
Powerlord Avatar answered Nov 07 '22 20:11

Powerlord