2つの異なるタイプのファイルを含む特定のフォルダの中で開くスクリプトを作成しています。 'secure'(secure.text、secure.001.textなど)ファイル、 'message'(message.txtなど)ファイルが含まれます。各ファイルには、年、日、日、時、分のログが含まれています。私はこれらのファイルをスキャンし、2006年1月のすべてのログエントリを含む新しいファイルを作成できるようにしたいと思います。このスクリプトの目的は、すべてのデータではなく、1セットのデータのみをスキャンできることですメッセージ)。スクリプトが入っているフォルダをスキャンして特定のファイルを検索するスクリプト[Perl]
現在の作業ディレクトリを見つけるスクリプトに問題があります。私の理解では、perlは現在のディレクトリとしてスクリプトの場所を使用します。私はopendirとclosedir関数を使用していて、スクリプトのディレクトリ内に60個のファイルがあることを確認していますが、テストするためにいくつかのファイルを削除すると、まだ60と表示され、カレントディレクトリ。正しい正規表現にもかかわらず、「安全」を見つけることができません。
私が得ている出力は「問題を見つけるファイル '安全」です。」
#!/usr/bin/perl
use strict;
use warnings;
#Locate and scan all of the files
#list all files in same dir as this perl script.
my $dirname = ".";
opendir(my $dh, $dirname) #sets $dh as the current working directory
or die "Can't open dir '$dirname':$!\n"; #Kills if can not open current directory.
my @all_the_file; #Instantiates new variable that accounts for all of the files in the current dir.
while(my $file = readdir($dh)) { #$file accounts for every file on device.
push(@all_the_file, $file); #Pushes files in current directory to $file.
}
closedir($dh);
#Gets all of the secure files.
my @all_the_secure_file;
@all_the_secure_file = grep(/^secure(\.\d{1,2})?$/, @all_the_file);
#Itterate over secure files.
my $filename = "secure";
open(my $fhin, "<", $filename)
or die "Can't open '$filename':$!\n";
chomp(my @lines = <$fhin>) ;
close($fhin);
#Match the Regex of Jan.
my @jan_lines = grep(/^Jan/ , @lines) ;
print "The file '$filename' = " . @lines . " lines.\n";
print "Size of \@jan_lines = " . @jan_lines . "\n";
#Print and create new file with Data.
my $filename2 = "secure.1";
open(my $fhin, "<", $filename)
or die "Can't open '$filename':$!\n";
chomp(my @lines2 = <$fhin>) ;
close($fhin);
my @jan_lines2 = grep(/^Jan/ , @lines2) ;
print "The file '$filename2' = " . @lines2 . " lines.\n";
print "Size of \@jan_lines2 = " . @jan_lines2 . "\n";
exit;
スクリプトの場所は、必ずしも現在の作業ディレクトリではありません。現在の作業ディレクトリは現在の作業ディレクトリです。例えば、[Cwd](http://perldoc.perl.org/Cwd.html)や[FindBin](http://perldoc.perl.org/FindBin.html)モジュールを調べてください。 –
また、 "安全なファイルを反復処理する"と "データを使って新しいファイルを印刷して作成する"というコメントは、実際には何もしません。 –
基本的なデバッグ:(1) '$ dirname'を実際のパスに設定しますハードコード)(2)あなたは 'opendir'から何を得るにはパスがありません!だから、 '$ dirname'を' opendir'が返すものの先頭に追加してください。 //そして、 '$ dirname'でファイルをスキャンします。 //テストするファイルを削除しないでください!スクリーンにプリントし、それらが正しいかどうかを調べるだけではどうですか?覚えておいて、彼らは完全な道を持つ必要があります。 'if(not -f $ file){print" No $ file \ n "}'でテストし、それらの_strings_(name '$ file')がシステム上の実際のファイルであるかどうかを見ることができます。 //他にも問題はありますが、これが始まりです。 – zdim