【发布时间】:2018-04-11 15:57:31
【问题描述】:
有很多关于在 PERL 上循环文件的文档,但是我遇到了一个我还没有找到解决方案的问题。我还没有找到任何在文本文件中循环工作的示例。
首先,我的环境:我在使用 macOS Sierra 版本 10.12.6 的 MacBook 上。我正在编写脚本并从 TextWrangler 版本 5.5.2 运行它们。
我想在下面的脚本中编写子 ProcessFile 来对我目录中文本文件的每一行进行字符串解析,但这根本没有运行。 TextWrangler 的 Unix Script Output.log 中没有输出。
#!/usr/bin/env perl
use strict;
use warnings;
my $dirName = "/Users/me/Documents/examples";
chdir $dirName or die "Cannot chdir $dirName: $!";
opendir ( my $dir, $dirName ) or die "Cannot open directory $dirName: $!";
my @files = readdir $dir;
# Put in variable for debugging with less than the full directory
#my $numberOfFiles = scalar( @files );
my $numberOfFiles = 10;
for ( my $iFiles = 0; $iFiles < $numberOfFiles; $iFiles++ )
{
# Check if .txt file
if ( $files[$iFiles]=~/\.txt$/ )
{
my $fileName = "$files[$iFiles]";
ProcessFile ( $fileName );
}
}
closedir $dir;
sub ProcessFile
{
my ( $fileName ) = @_;
print $fileName; print "\n";
open(my $inputFile, "<$fileName" ) or die "Cannot open file $fileName: $!";
while (my $line = <$inputFile>)
{
print "$line";
#Add parsing to gather metrics on the number of instances of different patterns
}
}
但是,如果我将 ProcessFile 更改为以下内容,它会打印文件的前 2 行:
sub ProcessFile
{
my ( $fileName ) = @_;
print $fileName; print "\n";
open(my $inputFile, "<$fileName" ) or die "Cannot open file $fileName: $!";
my $line = <$inputFile>;
print "$line";
my $line2 = <$inputFile>;
print "$line2";
}
另外,如果我将 ProcessFile 更改为以下内容,它会为文件中的每一行打印一行:
sub ProcessFile
{
my ( $fileName ) = @_;
print $fileName; print "\n";
open(my $inputFile, "<$fileName" ) or die "Cannot open file $fileName: $!";
my $i = 0;
while (my $line = <$inputFile>)
{
print "$i\n";
$i++;
}
}
在这一点上,我不确定下一步应该如何遍历文件的每一行并将其解析为字符串。最终我也想将匹配的字符串输出到文件中,但我需要先通过这个障碍。
【问题讨论】:
-
你为什么
chdir $dirName两次? -
尝试清理脚本以提出问题只是一个错误。我不需要发布整个脚本并错过了这个。清理干净了。
标签: perl text-parsing