Perl 目录

  • 目录

    以下是用于目录的标准函数。
    
    opendir DIRHANDLE, EXPR  # To open a directory
    readdir DIRHANDLE        # To read a directory
    rewinddir DIRHANDLE      # Positioning pointer to the begining
    telldir DIRHANDLE        # Returns current position of the dir
    seekdir DIRHANDLE, POS   # Pointing pointer to POS inside dir
    closedir DIRHANDLE       # Closing a directory.
    
  • 显示所有文件

    有多种方法可以列出特定目录中所有可用的文件。首先,让我们使用简单的方法通过glob运算符获取并列出所有文件-
    
    # Display all the files in /tmp directory.
    $dir = "/tmp/*";
    my @files = glob( $dir );
    
    foreach (@files ) {
       print $_ . "\n";
    }
    
    # Display all the C source files in /tmp directory.
    $dir = "/tmp/*.c";
    @files = glob( $dir );
    
    foreach (@files ) {
       print $_ . "\n";
    }
    
    # Display all the hidden files.
    $dir = "/tmp/.*";
    @files = glob( $dir );
    foreach (@files ) {
       print $_ . "\n";
    }
    
    # Display all the files from /tmp and /home directories.
    $dir = "/tmp/* /home/*";
    @files = glob( $dir );
    
    foreach (@files ) {
       print $_ . "\n";
    }
    
    这是另一个示例,它打开一个目录并列出该目录中所有可用的文件。
    
    opendir (DIR, '.') or die "Couldn't open directory, $!";
    while ($file = readdir DIR) {
       print "$file\n";
    }
    closedir DIR;
    
    打印您可能只想列出的C源文件列表的另一个示例是-
    
    opendir(DIR, '.') or die "Couldn't open directory, $!";
    foreach (sort grep(/^.*\.c$/,readdir(DIR))) {
       print "$_\n";
    }
    closedir DIR;
    
  • 建立新目录

    您可以使用 mkdir 函数来创建新目录。您将需要具有创建目录所需的权限。
    
    $dir = "/tmp/perl";
    
    # This creates perl directory in /tmp directory.
    mkdir( $dir ) or die "Couldn't create $dir directory, $!";
    print "Directory created successfully\n";
    
  • 删除目录

    您可以使用 rmdir 函数删除目录。您将需要具有所需的权限才能删除目录。此外,在尝试删除该目录之前,该目录应该为空。
    
    $dir = "/tmp/perl";
    
    # This removes perl directory from /tmp directory.
    rmdir( $dir ) or die "Couldn't remove $dir directory, $!";
    print "Directory removed successfully\n";
    
  • 变更目录

    您可以使用 chdir 函数来更改目录并转到新位置。您将需要具有所需的权限才能更改目录并进入新目录。
    
    $dir = "/home";
    
    # This changes perl directory  and moves you inside /home directory.
    chdir( $dir ) or die "Couldn't go inside $dir directory, $!";
    print "Your new location is $dir\n";