PDA

View Full Version : removing '.' and '..' from readdir


hogtied
03-18-2003, 05:33 AM
Hello members.

I have a script that reads the directory contents into an array. The only thing is that i also captures the parent directories.

Without using "shift" is there another way of doing this?


Thanks
Hogtied

chrisvmarle
03-18-2003, 07:49 AM
If you use a foreach-loop (wich is often used with readdir) you could do this:

@files = readdir(DIR);

foreach $file (@files) {
next if (substr($file,0,1) eq ".");
#other actions here
}

I hope this helps

Mzzl, Chris

hogtied
03-18-2003, 07:58 PM
ill give that a try thanks

mellin
03-18-2003, 09:08 PM
You could also use grep if operating under Linux/Unix.

-----------
@dir_content = grep(/^.+\..+$/, readdir(DIR_FILEHANDLE));
-----------

Which would push to array only those files, that have name and extension, such as file.xml or text.txt

hogtied
03-19-2003, 09:36 PM
@files = readdir(DIR);

foreach $file (@files) {
next if (substr($file,0,1) eq ".");
#other actions here
}


sorry chris but your script did not work. It still returned the parent directories....

hogtied
03-19-2003, 09:57 PM
-----------
@dir_content = grep(/^.+\..+$/, readdir(DIR_FILEHANDLE));
-----------


hey millen this did work except I don't want the files in it, I want the subdirectories..

Thanks though.. this could be useful elsewhere.

ian17
03-31-2003, 05:22 PM
This works well for me. It's elegant but I agree it's not easy to read.

my $path= "/home/whatever";
opendir DIR_FILEHANDLE, $path;
@dir_content =
sort
grep -d,
map "$path/$_",
grep !/^\./,
readdir(DIR_FILEHANDLE));

You can leave out the line 'sort' if you don't want your directories in alphabetic order.
grep -d, (don't miss the comma) identifies directories
map presents the full path&filename for grep -d to work on
grep !/^\./, excludes directories starting with . so it excludes hidden directories like .profile as well.