Lecture#12

Chapter 12 - Directory Operations


Chdir
chdir is like cd:

chdir "/tmp"; # Changes current directory to /tmp $! will be set if there's an error
chdir; #changes to your home directory...doesn't use $_


Globbing
The shell globs (expands filenames) automatically:

if we have the following program:

#!/usr/local/bin/perl
foreach $filename (@ARGV) {
   print "Filename: $filename\n";
}

./myprg *.txt will expand the *.txt will be expanded into a list of all the files that end in .txt so, if there were 3 files in the current directory that ended in .txt, it would be the same as typing:

./myprg.pl one.txt two.txt three.txt

The @ARGV variable is a special array that gobbles up all of the command line arguments.

You can also have Perl perform a similar function using the glob operator:

#!/usr/local/bin/perl
@textfiles = glob "*.txt";
foreach $filename (@textfiles) {
   print "Filename: $filename\n";
}

We could have gotten all the .txt and .pl files if we did the following:

@textfiles = glob "*.txt *.pl"; #Just separated them with a space

Glob also has an alternate syntax if you prefer....

@textfiles = <*.txt *.pl>; #Looks too much like a filehandle...I'd use glob


Directory Handles
There's a special way to read the filenames in a directory. There's an operator we're not really going to go over that will let you read from a file, read, because you don't really need to use it, but for directories, here's how you do it:

opendir DH, "/tmp";             #Notice opendir has specified this is a directory
while ($file = readdir DH) {   #Using readdir
   print "Filename: $file\n";
}
closedir DH;                          #Command to close directories


CSC255 - Alan Watkins - North Carolina State University