Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I am using ActivePerl on a windows 2000 machine. My script reads all the files in a directory, does some reformating and plops them all into one big file in another directory. My script wrks if I have the .pl in the same dirctory as the files and use the ".". But, If i use a path to the directory it does not work. Any thoughts. thanks for any info, Bernie
#!/usr/bin/perl #Parses web log and reformats opendir(DIR, 'c:\perl\test'); ##If . is used and .pl is in the same d +ir as files it works! @files = readdir(DIR); close(DIR); foreach $file (@files) { $name = $file; @filename = split (/\./, $name); # open (MYFILE, ">myfile.txt"); open( THEFILE,$file ) ; @theList = <THEFILE>; close( THEFILE ); foreach( @theList ) { s/\/uid=/,/; s/LDAP:\/\///; s/ou=//g; s/o=//; @theLine = split( /\s*,\s*/ ); print "\"$theLine[0]\",\"$theL +ine[1]\",$theLine[2]\",\"$theLine[3]\",\"$theLine[4]\",\"$theLine[5]\ +",\"$theLine[6],\"$filename[0]\",\"$filename[1]\",$theLine[7] \n"; } } exit( 0 );

Replies are listed 'Best First'.
Re: Directory Stuff
by Jenda (Abbot) on Apr 18, 2003 at 14:41 UTC

    readdir() returns just the NAME of the file, not the PATH! Therefore if you

    opendir DIR, $path
    you have to
    open THEFILE, "< $path/$file" or die "Can't open $path/$file: $!\n";

    HTH, Jenda
    Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.
       -- Rick Osborne

    Edit by castaway: Closed small tag in signature

Re: Directory Stuff
by dws (Chancellor) on Apr 18, 2003 at 15:49 UTC
    But, If i use a path to the directory it does not work.

    You might have been able to figure this out for yourself if your script didn't ignore useful clues. If a library routine returns an error by setting $!, check it! That means writing

    opendir(DIR, 'c:/perl/test') or die "c:/perl/test: $!"; ... open(MYFILE, ">myfile.txt") or die "myfile.txt: $!"; open(THEFILE, "<$file") or die "$file: $!"; ...
    Purists will tell you to also do
    close(MYFILE) or die "c:/perl/test: $!";
    in case the disk fills up and the script is unable to cleanly close the file.

    That said, understanding that readdir() returns names, not paths, is key to understanding the problem. Here, consulting the perl documentation help. The blurb on readdir() in perlfunc spells it right out:

    If you're planning to filetest the return values out of a readdir, you'd better prepend the directory in question. Otherwise, because we didn't chdir there, it would have been testing the wrong file.