Perl Directory Operations

The following lists some standard functions for directory operations:

opendir DIRHANDLE, EXPR  # 打开目录
readdir DIRHANDLE        # 读取目录
rewinddir DIRHANDLE      # 定位指针到开头
telldir DIRHANDLE        # 返回目录的当前位置
seekdir DIRHANDLE, POS   # 定位指定到目录的 POS 位置
closedir DIRHANDLE       # 关闭目录

Display all files

Display all files in the directory. The following example uses the glob operator, as demonstrated below:

Example

#!/usr/bin/perl # Display all files in the /tmp directory $dir = "/tmp/*"; my @files = glob( $dir ); foreach (@files ){ print $_ . "\n"; } # Display all files ending with .c in the /tmp directory $dir = "/tmp/*.c"; @files = glob( $dir ); foreach (@files ){ print $_ . "\n"; } # Display all hidden files $dir = "/tmp/.*"; @files = glob( $dir ); foreach (@files ){ print $_ . "\n"; } # Display all files in the /tmp and /home directories $dir = "/tmp/* /home/*"; @files = glob( $dir ); foreach (@files ){ print $_ . "\n"; }

The following example can list all files in the current directory:

Example

#!/usr/bin/perl opendir (DIR, '.') or die "Cannot open directory,$!"; while ($file = readdir DIR) { print "$file\n"; } closedir DIR;

If you want to display all files ending with .c in the /tmp directory, you can use the following code:

Example

#!/usr/bin/perl opendir(DIR, '.') or die "Cannot open directory,$!"; foreach (sort grep(/^.*\.c$/,readdir(DIR))){ print "$_\n"; } closedir DIR;

Create a new directory

We can use themkdirfunction to create a new directory. Before executing, you need to have sufficient permissions to create the directory:

Example

#!/usr/bin/perl $dir = "/tmp/perl"; # Create the perl directory under /tmp mkdir( $dir ) or die "Cannot create$dirdirectory,$!"; print "Directory created successfully\n";

Delete a directory

We can use thermdirfunction to delete a directory. Sufficient permissions are required to perform this operation. Additionally, the directory to be deleted must be an empty directory:

Example

#!/usr/bin/perl $dir = "/tmp/perl"; # Delete the perl directory under /tmp rmdir( $dir ) or die "Cannot delete$dirdirectory,$!"; print "Directory deleted successfully\n";

Change directory

We can use thechdirfunction to switch the current directory. Sufficient permissions are required to perform this operation. Example:

Example

#!/usr/bin/perl $dir = "/home"; # Move the current directory to /home chdir( $dir ) or die "Cannot switch directory to$dir , $!"; print "Your current directory is$dir\n";

Executing the above program, the output result is:

你现在所在的目录为 /home
Other extensions