
mhx
Enthusiast
/ Moderator
Jul 2, 2001, 10:03 PM
Post #11 of 22
(2024 views)
|
One interesting thing i noticed was when i left the $dir empty it did the contents of c:/ not the contents of the folder that the script was in. So i was wondering if that could be my problem with the cgi script. Do i need the full path to the directory i want to sort? No, a relative path will be sufficient. If you want the contents of the current directory, just say
Also say i just wanted to print the first ten most recent files. To print only the 'top ten', use an array slice. I've reprinted the whole code here:
#!/bin/perl -w use strict; my $dir = '.'; # current directory opendir DIR, $dir or die "cannot open '$dir': $!\n"; my @files = map "$_->[0]\n", sort { $b->[1] <=> $a->[1] } map [$_, (stat)[9]], readdir DIR; closedir DIR; print @files[0..9]; # print elements 0 to 9 (top ten) Also, I've found a third way of getting the newline sequence in. I've put it into the already existing map, so the print statement looks a bit nicer and it saves you an addition join. With an array slice, you can cut elements out of an array by their index. Array slices are not limited to ranges, you can specify arbitrary indices in the square brackets. You could even use another array that would hold indices for an array slice. For example,
my @a = ('A'..'Z', ' '); my @i = (15, 4, 17, 11); print @a[@i,-1,7,0,2,10,@i[1..2]]; will print "PERL HACKER". You can try to find out why it prints this. If you got this, you will definetely know how array slices work. As you can see, in the slice I'm using an array (@i), some arbitrary indices (including -1, which refers to the last index) and even another array slice (@i[1..2]). There are also hash slices, and they work in quite the same way:
my %t = ( sec => 42, min => 5, hour => 7, day => 3, month => 7, year => 2000, ); print "It's ", join '-', @t{year,month,day}; You could even use this to print the hash values sorted by the keys of the hash:
print "@t{sort keys %t}"; I hope this helps and makes the slicing technique a bit clearer. -- Marcus
|