Perl has a special tool to provide the same service for inside scripts. This tool is called glob. This is a function that takes one argument a string with file name pattern and returns a list of files in the current directory with names matching this pattern. Patterns can contain symbols * (meaning: any number of letters or digits) and ? (meaning: any letter or digit). Thus, to get all Perl scripts in the current directory inside a Perl script we can use code like this
my @scripts = glob("*.pl");
foreach (@scripts){ print "$_\n"; }
If we need to get the list of all files we need to use pattern "*". We also may specify a name of the directory
where we want to get the list of files and then a pattern. For example, to print all files in a directory whose name is
in variable $dir we do this:
my $dir = "../oracle";
foreach ( glob("$dir/*") ){
print "$_\n";
}
glob function also allows us to provide several patterns in one argument string, In this situation patterns should be separated with spaces. For example, the following code prints names of all files that start with p or s:
for ( glob "p* s*" ){
print "$_\n";
}
chdir("/homes/james") or die("Cannot change a directory\n");
If we omit the parameter, Perl determines the home directory as best possible and attempts to set the working directory
to the home directory. This is one of few places where omitting the parameter doesn't use $_.
$deleted = unlink "fred", "wilma"; print "$deleted file(s) deleted.\n";We can also use any array containing file names as an argument of the function unlink or the result of the glob function. For example, we can remove all files from the current directory by running:
unlink glob "*";However, I wouldn't recommend to test such a script
.
for ( glob "*" ){
unless( rename $_, lc($_) ){
warn "Cannot rename file '$_' to '".lc($_)."'\n";
}
}
In this script we used two new functions:
Using rename function we can also move files around. That is, our file names may include directories as well. For example, the following command moves file fred from directory /oracle into the current directory:
rename "/oracle/fred", "fred";
To remove a directory we need to use function rmdir. This function takes only one argument - the name of the directory to remove and returns true upon success, false on fail. Combining these two functions we can create a temporary directory for our script to work in and remove this directory when the job is done:
my $temp_dir = "$_my_script_temp_$"; mkdir $temp_dir; chdir $temp_dir; ... chdir ".."; rmdir $temp_dir;