Re: list of fles in a directory, but use wildcards like *
by Zaxo (Archbishop) on Sep 04, 2003 at 16:12 UTC
|
| [reply] |
|
|
opendir DIR, $dir;
my @file = grep { $_ ne '.' && $_ ne '..' } readdir DIR;
closedir DIR;
to list all files in the directory, opening those files with,
foreach $file (@file){
open(MYFILE, $dir.$file[$i]) or die qq(Cannot open $file[$i]\n);
....some other stuff
would work. But now using the glob, it's dying when open the files in the files list.
| [reply] [d/l] [select] |
|
|
| [reply] |
|
|
foreach $file (@file){
open(MYFILE, $dir.$file[$i]) or die qq(Cannot open $file[$i]\n);
...
Well, in addition to the previous comment about the directory path (which is correct), this snippet would not do what you want because you aren't setting $i; you are using the scalar $file as an iterator variable, which is being set to successive elements of array @file, but then in the loop you are always using the "$i'th" element of @file, and you don't show any indication that this (totally unnecessary) array index counter is being set or incremented.
On top of that, your error report is misleading: you try to open a file called $dir.$file[$i] and when that fails, you only report trying to open $file[$i], so you would never know when the problem is due to the content of $dir.
| [reply] [d/l] [select] |
Re: list of fles in a directory, but use wildcards like *
by hardburn (Abbot) on Sep 04, 2003 at 16:14 UTC
|
my @files = <onlythese*.txt>;
Not to be confused with the readline operator.
---- I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
-- Schemer
Note: All code is untested, unless otherwise stated
| [reply] [d/l] |
Re: list of fles in a directory, but use wildcards like *
by simonm (Vicar) on Sep 04, 2003 at 16:28 UTC
|
In addition to the glob operator shown above, you can also do this checking in Perl, using its regular expression syntax instead of the local shell's:
my @files = grep { /^onlythese.*\.txt$/ } readdir DIR;
| [reply] [d/l] |
|
|
simonm,
Just a nit
While this works nearly 100% the same as the glob, it is not exactly the same. This is because some operating systems, *nix for instance, support imbedded newlines in file names. I would recommend adding the s modifier, using something like (\d|\D)* in place of .*, or just annotating that it won't match files with imbbedded newlines.
Cheers - L~R
| [reply] |
|
|
To continue with Limbic~Region's nit, file names can
even have newlines at the end, in which case using
$ will cause the regex to match, for example,
"onlythese1.txt\n". It will rarely if ever happen, but I
tend to use \z to match the literal end of
string, just in case.
my @files = grep { /^onlythese.*\.txt\z/s } readdir DIR;
-- Mike
--
XML::Simpler does not require XML::Parser or a SAX parser.
It does require File::Slurp.
-- grantm, perldoc XML::Simpler | [reply] [d/l] [select] |