Perl-directories

提供:Dev Guides
移動先:案内検索

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 演算子を使用して、すべてのファイルを取得およびリストする簡単な方法を使用しましょう-

#!/usr/bin/perl

# 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";
}

ディレクトリを開き、このディレクトリ内で使用可能なすべてのファイルをリストする別の例を次に示します。

#!/usr/bin/perl

opendir (DIR, '.') or die "Couldn't open directory, $!";
while ($file = readdir DIR) {
   print "$file\n";
}
closedir DIR;

使用する可能性のあるCソースファイルのリストを印刷するもう1つの例は-

#!/usr/bin/perl

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

新しいディレクトリを作成

*mkdir* 関数を使用して、新しいディレクトリを作成できます。 ディレクトリを作成するには、必要な権限が必要です。
#!/usr/bin/perl

$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* 関数を使用して、ディレクトリを削除できます。 ディレクトリを削除するには、必要な権限が必要です。 さらに、このディレクトリを削除する前に空にする必要があります。
#!/usr/bin/perl

$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* 関数を使用して、ディレクトリを変更し、新しい場所に移動できます。 ディレクトリを変更し、新しいディレクトリ内に移動するには、必要な権限が必要です。
#!/usr/bin/perl

$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";