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: Windows Explorer exits unexpectedly Windows XP Pro
    ... another FYI - I did the same thing on our windows 2000 and 2003 ... This gz extensiion is a unix extension from the ... for this on XP Pro. ...
    (microsoft.public.windowsxp.help_and_support)
  • Re: Windows Explorer exits unexpectedly Windows XP Pro
    ... This gz extensiion is a unix ... extension from the gzip command. ... Computer: JAXSCLIFTONADM ... Plus mine is an archive type file. ...
    (microsoft.public.windowsxp.help_and_support)
  • Re: Ada.Directories.Base_Name and dot files
    ... (AARM A.16(1.a)) ... The null string design baffles me. ... "extension" name, Unix is a lot ...
    (comp.lang.ada)
  • 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)