|
Processing all files in a directory - Perl
From this week's Perl course:
opendir(DH, ".");
while ($igot = readdir(DH)) {
next if ($igot =~ /^\.{1,2}$/);
print "igot $igot\n";
}
You'll notice that I have used a regular expression to check for files called dot and dot-dot, which are the current and parent directory, as I typically would NOT want to process each of them in my loop.
Other alternatives ... this is Perl so "There is more than one way" ... include:
@files = glob("*");
@files = <*>
@files = `ls`
but although each of these is shorter, they are not recommended for heavy directory traversal applications - in each case, they return you a sorted list of names and that sorting can be useful for a single directory, but wasteful in a heavier application that's going through a large number of directories.
Once you are traversing a directory, you can do all sorts of things - use operators such as -d to find out what is a subdirectory, and -s to find the size of individual contents, for example.
If you want to find the biggest file in or below a directory (perhaps you're running out of disc space?), we have a sample program here from our Perl for larger projects course. (written 2008-10-11 07:25:48)
Associated topics are indexed under P215 - Perl - More about FilesP602 - Perl - Advanced File and Directory Handling
Some other Articles
Next in the sequence - courses next year (2009)23:30 bookings and midnight checkinsSeend, near Melksham, WiltshireWeb Bloopers - good form design - avoiding pitfallsProcessing all files in a directory - PerlText formating for HTML, with PHPCaen Hill and Olivers CastleDont bother to write a Perl programPerl - map to process every member of a list (array)What a shock
|
1892 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38 at 50 posts per page
This is a page archived from The Horse's Mouth at
http://www.wellho.net/horse/ -
the diary and writings of Graham Ellis.
Every attempt was made to provide current information at the time the
page was written, but things do move forward in our business - new software
releases, price changes, new techniques. Please check back via
our main site for current courses,
prices, versions, etc - any mention of a price in "The Horse's Mouth"
cannot be taken as an offer to supply at that price.
Link to Ezine home page (for reading).
Link to Blogging home page (to add comments).
|
|