chdir "/tmp"; # Changes current directory to /tmp $! will be set if there's an error
chdir; #changes to your home directory...doesn't use $_
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
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