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 Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Simple newbie help 1

Status
Not open for further replies.

bluegroper

Technical User
Dec 12, 2002
407
AU
Hi forum
I have simple code snippet as below.
It works, but I'd like to learn a better way to write the 2 next statements on 1 line.
Something like
next if ($filename eq ".") OR if ($filename eq "..");
(thinks I canna find the right places for brackets)
or
next if ($filename eq "[.|..]");
Much TIA's
Code:
while ($filename = readdir TEMP) {
  next if ($filename eq ".");
  next if ($filename eq "..");
  ... process something here ...
}
 
Another option which will get you in and out of the directory itself a little faster:
Code:
opendir(TEMP, $src_dir) || die "Can't open $src_dir" ;
@file_list = grep !/^\.{1,2}$/, readdir TEMP ;
closedir TEMP ;

foreach $filename (@file_list) {
  next if (! -f "$src_dir/$filename") ;
  # process filename
};

The bonus I like about this one is that the code spends less time with an open directory handle and I can pass the list of files off to another routine if needed. There is probably a better RE out there but it isn't coming to mind right now.
 
You don't need a regexp to filter . and .. out of a directory list:

Code:
opendir(TEMP, $src_dir) || die "Can't open $src_dir" ;
@file_list = grep {$_ ne '.' && $_ ne '..'} readdir TEMP ;
closedir TEMP;

How much faster/slower it is than using a regular expression can be determined using benchmark. I assume it is faster.

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
For efficiency, and legibility (a bit fanatical about that),
I like to combine both suggestions!
Code:
opendir(TEMP, $tmpdir) or die "Cannot open $tmpdir : $!" ;
@files = readdir TEMP;
closedir TEMP ;
foreach $filename (@files) {
	next if $filename eq "." or $filename eq "..";
	... process files/filenames ...
}
Thanks for the instruction and much cheers to all
 
I don't know of any common operating system that does not use . and .. so to save processing it is faster to do something like this:

Code:
opendir(TEMP, $tmpdir) or die "Cannot open $tmpdir : $!" ;
@files = readdir TEMP;
closedir TEMP ;
for my $i (2..$#files) {
   process $files[$i]
}




------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Code:
for my $i (2..$#files) {
   process $files[$i]
}
I might be a little leery on that one. Taking too much for granted. While uncommon, there are files that will sort in front of '.' Guess it depends on how well you trust your environment.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top