berkay
berkay

Reputation: 3967

How to read files in a directory, open it and get the words for each line in perl?

i'm trying to write a perl script, first it opens a directory (There are more then one files in the directory), second it reads the files in the directory, then line by line puts the words in an array and sends these words to a c++ program as an argument. i tried to write the script but there is a problem when processing the files, it opens the directory but i can not access the files,

there should be more than one answer to this kind of problem, my script is:

my $directory = '.';
my @connection;
opendir (DIR, $directory) or die $!;

    while (my $file = readdir(DIR)) {
            next if ($file =~ m/^\./);
            print "$file\n";
            open (MYFILE, '$file') or die $!;# error is in here, can not open/
            while (<MYFILE>)
            {
            # split each input line; words are separated by whitespace
                    for $word (split)
                    {
                            #put the words in an array
                            #no need to store words, can be overwritten in array
                            #system() for calling c++ code
                    }
            }
    }

Upvotes: 1

Views: 204

Answers (1)

moinudin
moinudin

Reputation: 138347

Remove the '' quotes around $file:

open (MYFILE, $file) or die $!;

In Perl, single quotes will quote the string literally and interprets nothing. You need to use double quotes if you want escaped characters and variable names to be interpreted. However, in this case where you only have a variable and nothing else you shouldn't quote it at all, even though technically "$file" is correct.

Upvotes: 2

Related Questions