Perl Directory Operations
The following lists some standard functions for operating on directories:
opendir DIRHANDLE, EXPR # 打开目录
readdir DIRHANDLE # 读取目录
rewinddir DIRHANDLE # 定位指针到开头
telldir DIRHANDLE # 返回目录的当前位置
seekdir DIRHANDLE, POS # 定位指定到目录的 POS 位置
closedir DIRHANDLE # 关闭目录
Display all files
To display all files in a directory, the following example uses the glob operator, demonstrated below:
Example
#!/usr/bin/perl
Display all files in the /tmp directory
$dir
=
"
/tmp/*
"
;
my
@files
=
glob
(
$dir
)
;
foreach
(
@files
)
{
$_
.
"
\n
"
;
}
Display all files ending in .c in the /tmp directory
$dir
=
"
/tmp/*.c
"
;
@files
=
glob
(
$dir
)
;
foreach
(
@files
)
{
$_
.
"
\n
"
;
}
Display all hidden files
$dir
=
"
/tmp/.*
"
;
@files
=
glob
(
$dir
)
;
foreach
(
@files
)
{
$_
.
"
\n
"
;
}
Display all files in the /tmp and /home directories
$dir
=
"
/tmp/* /home/*
"
;
@files
=
glob
(
$dir
)
;
foreach
(
@files
)
{
$_
.
"
\n
"
;
}
The following example can list all files in the current directory:
Example
#!/usr/bin/perl
opendir
(
DIR
,
'
.
'
)
or
die
"
Unable to open directory,
$!
"
;
while
(
$file
=
readdir
DIR
)
{
"
$file
\n
"
;
}
closedir
DIR
;
If you want to display all files ending in .c in the /tmp directory, you can use the following code:
Example
#!/usr/bin/perl
opendir
(
DIR
,
'
.
'
)
or
die
"
Unable to open directory,
$!
"
;
foreach
(
sort
grep
(
/^.*.
c
$/,
readdir
(
DIR
)
)
)
{
"
$_
\n
"
;
}
closedir
DIR
;
Create a new directory
We can use the mkdir function to create a new directory; before executing, you need sufficient permissions to create the directory:
Example
#!/usr/bin/perl
$dir
=
"
/tmp/perl
"
;
Create a perl directory under the /tmp directory
mkdir
(
$dir
)
or
die
"
Unable to create
$dir
directory,
$!
"
;
"
Directory created successfully
\n
"
;
Delete directory
We can use the rmdir function to delete a directory; performing this operation requires sufficient permissions. In addition, the directory to be deleted must be empty:
Example
#!/usr/bin/perl
$dir
=
"
/tmp/perl
"
;
Delete the perl directory under the /tmp directory
rmdir
(
$dir
)
or
die
"
Unable to delete
$dir
directory,
$!
"
;
"
Directory deleted successfully
\n
"
;
Change directory
We can use thechdir function to change the current directory; performing this operation requires sufficient permissions. Example below:
Example
#!/usr/bin/perl
$dir
=
"
/home
"
;
Change the current directory to the /home directory
chdir
(
$dir
)
or
die
"
Unable to change directory to
$dir
,
$!
"
;
"
You are now in the directory
$dir
\n
"
;
Running the above program, the output is:
你现在所在的目录为 /home