Multiple text parsing and writing using the while statement, the diamond operator <> and $ARGV variable in Perl

StackOverflow https://stackoverflow.com/questions/16733298

I have some text files, inside a directory and i want to parse their content and write it to a file. So far the code i am using is this:

#!/usr/bin/perl

#The while loop repeats the execution of a block as long as a certain condition is evaluated true

use strict; # Always!
use warnings; # Always!

my $header = 1; # Flag to tell us to print the header
while (<*.txt>) { # read a line from a file
    if ($header) {
        # This is the first line, print the name of the file
        **print "========= $ARGV ========\n";**
        # reset the flag to a false value
        $header = undef;
    }
    # Print out what we just read in
    print;
}
continue { # This happens before the next iteration of the loop
    # Check if we finished the previous file
    $header = 1 if eof;
}

When i run this script i am only getting the headers of the files, plus a compiled.txt entry. I also receive the following message in cmd : use of uninitialized $ARGV in concatenation <.> or string at concat.pl line 12

So i guess i am doing something wrong and $ARGV isn't used at all. Plus instead of $header i should use something else in order to retrieve the text.

Need some assistance!

有帮助吗?

解决方案

<*.txt> does not read a line from a file, even if you say so in a comment. It runs

glob '*.txt'

i.e. the while loop iterates over the file names, not over their contents. Use empty <> to iterate over all the files.

BTW, instead of $header = undef, you can use undef $header.

其他提示

As I understand you want to print a header with the filename just before the first line, and concatenate them all to a new one. Then a one-liner could be enough for the task.

It checks first line with variable $. and closes the filehandle to reset its value between different input files:

perl -pe 'printf qq|=== %s ===\n|, $ARGV if $. == 1; close ARGV if eof' *.txt

An example in my machine yields:

=== file1.txt ===
one
=== file2.txt ===
one
two
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top