Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Perl custom sort

Status
Not open for further replies.

droid99

Programmer
Joined
Jul 6, 2004
Messages
5
Location
US
I'm looking for an efficient way to sort the following in perl:

/this/is/the/file/path/June/n06302004_2004063009.html
/this/is/the/file/path/July/n07012004_2004070108.html
/this/is/the/file/path/July/n07012004_2004070103.html
/this/is/the/file/path/July/n07012004_2004070109.html

I need to sort the above in descending order by the filename, not the entire path (n06302004_2004063009.html, etc.) so that it looks like:

/this/is/the/file/path/July/n07012004_2004070109.html
/this/is/the/file/path/July/n07012004_2004070108.html
/this/is/the/file/path/July/n07012004_2004070103.html
/this/is/the/file/path/June/n06302004_2004063009.html

Is there a way to pick out the filenames out of the path, sort by the filename, while preserving the entire filepath? Perhaps by a perl custom sort?

Any help would be appreciated. Thanks.


 
rather than giving you an entire answer... I will if you like... try adapting this script i've just written:-

Code:
#!/usr/bin/perl

while (<DATA>) {
  chomp;
  m|^.*/([^/]+)$|;
  print "$1\n";
}

__DATA__
/this/is/the/file/path/June/n06302004_2004063009.html
/this/is/the/file/path/July/n07012004_2004070108.html
/this/is/the/file/path/July/n07012004_2004070103.html
/this/is/the/file/path/July/n07012004_2004070109.html

I suggest pushing the capture of $1 into an array and then sorting that :-)


Kind Regards
Duncan
 
I'd suggest using File::Basename to get the filename and then using a Schwartzian Transformation to sort, like so:

Code:
#/!usr/bin/perl -w
use strict;
use File::Basename;

# array of filenames, with path
my @files = qw!
/this/is/the/file/path/June/n06302004_2004063009.html
/this/is/the/file/path/July/n07012004_2004070108.html
/this/is/the/file/path/July/n07012004_2004070103.html
/this/is/the/file/path/July/n07012004_2004070109.html
!;

# sort by filename
my @sorted =    map { $_->[0] }
                sort { $b->[1] cmp $a->[1] }
                map { [ $_, basename $_ ] } @files;

# print the result
print $_,"\n" for (@sorted);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top