sort files by extension

From: Perl.Org (perl.org_at_jpw3.com)
Date: 07/28/04


To: beginners@perl.org
Date: Wed, 28 Jul 2004 13:27:53 -0400

I have a list of files I want to case-insensitive sort by extension, files
with no extension appearing first. It should handle both Windows and Unix
directory separators. I think I have working code, but I am interested in the
various syntax for this one - there MUST be a better way than my feeble attempt:

use strict;

my @input = ( '/path/to/file/with.ext', '/path/to/file/with.htm',
'/path/to/file/without', '/path/to/file/with.eml', '/path/to/file/with.pdf' );
my @output = sort
{
  my $ex1 = '';
  my $ex2 = '';

  if ( $a =~ m#[^\\/]\.([^\\/]+)$# )
  {
    $ex1 = $1;
  }

  if ( $b =~ m#[^\\/]\.([^\\/]+)$# )
  {
    $ex2 = $1;
  }

  return( lc( $ex1 ) cmp lc( $ex2 ));
} @input;

print join( $/, @output );

C:\temp>sortext.pl
/path/to/file/without
/path/to/file/with.eml
/path/to/file/with.ext
/path/to/file/with.htm
/path/to/file/with.pdf



Relevant Pages

  • Re: Windows Media Player executes WMF content in .MP3 files.
    ... >In the UNIX world, how a file is executed always depends on any magic ... and never on the filename. ... In the Microsoft world, the file extension counts to decide what operations ...
    (comp.security.misc)
  • Re: DCL versus Unix CLIs, was: Re: File output like Unix
    ... Why include Unix? ... And this from the file system limitations of Linux and Unix, of OpenVMS or of Windows. ... As with your example from Linux and Unix, OpenVMS also doesn't have a particular hard-coded meaning of a file extension, either. ... I am not sure how it has evolved in OS X, but traditionally a Mac user sees a single file, but the file system actually has two parts - a "data fork" and a "resource fork". ...
    (comp.os.vms)
  • Re: Creating a CD on Unix
    ... > I am trying to create a CD on a Solaris environment. ... > case and to keep Unix from chopping off the extension? ... file names, owners and permissions. ...
    (comp.unix.admin)
  • Re: Windows Media Player executes WMF content in .MP3 files.
    ... and never on the filename. ... >You have a much smarter user than I dealt with in my time with Unix users. ... there should not be such conventions. ... Not naming a text file with a .txt extension, ...
    (comp.security.misc)
  • Re: Making structures useable
    ... > keyword as an extension to REDUCE so that it can act like the Unix ...
    (comp.lang.lisp)