在Mac上的PERL中循环显示文本文件中的行,无法在while循环中打印行

时间:2018-04-11 15:57:31

标签: perl text-parsing

有很多关于在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更改为以下内容,则会打印文件的前两行:

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++;
    }
}

此时我不确定下一步应该是什么才能遍历文件的每一行并将其解析为字符串。最终我也想要将匹配的字符串输出到文件中,但我需要先通过这个障碍。

1 个答案:

答案 0 :(得分:1)

必须是编辑/ IDE问题。您的原始代码工作正常。我用3个txt文件创建了目录,运行了你的代码,这里是输出:

[18:04:40][filip@lap2:~]$ more /Users/me/Documents/examples/*
::::::::::::::
/Users/me/Documents/examples/a.txt
::::::::::::::
a
a
a
::::::::::::::
/Users/me/Documents/examples/b.txt
::::::::::::::
b
b
b
::::::::::::::
/Users/me/Documents/examples/c.txt
::::::::::::::
c
c
c
[18:04:48][filip@lap2:~]$ perl 49779605.pl 
b.txt
b
b
b
c.txt
c
c
c
a.txt
a
a
a
Use of uninitialized value within @files in pattern match (m//) at 49779605.pl line 23.
Use of uninitialized value within @files in pattern match (m//) at 49779605.pl line 23.
Use of uninitialized value within @files in pattern match (m//) at 49779605.pl line 23.
Use of uninitialized value within @files in pattern match (m//) at 49779605.pl line 23.
Use of uninitialized value within @files in pattern match (m//) at 49779605.pl line 23.