|
Posted by Ben Morrow on March 7, 2008, 11:08 pm
Please log in for more thread options
> hello. i have code (below) that sorts the contents of a directory. it
> works fine, but i need to show only files that start with an 'R'.
> thanks in advance for your help.
perldoc -f grep
> opendir(STOCKBACKGROUND, ".") || &error("STOCKBACKGROUND");
Use lexical filehandles in non-ancient versions of Perl (since 5.6.0).
Don't call subs with & unless you need the special effects that causes.
Include the system error and what you were trying to do in the error
message.
I would recommend using 'or' instead of '||', as you can then drop the
parens. You may not like that style, though.
opendir my $STOCKBACKGROUND, "." or error "can't opendir '.': $!";
> @stockbackgrounds = readdir(STOCKBACKGROUND);
You should have
use strict;
at the top of your script; this line will the need to become
my @stockbackgrounds = readdir($STOCKBACKGROUND);
> @stockbackgrounds = sort {lc($a) cmp lc($b)} @stockbackgrounds;
> closedir(STOCKBACKGROUND);
I would do this all in one go, without the intermediate assignments;
also, if you use lexical filehandles they close themselves at the end of
the block they are in, so you can simply write
my @stockbackgrounds = do {
opendir my $D, '.' or error "can't opendir '.': $!";
sort { lc($a) cmp lc($b) }
grep /^R/, readdir $D;
};
You may find that too compressed, though.
Ben
|