Cool_Coder
Cool_Coder

Reputation: 5083

opening file in perl gives errors?

I am writing a perl script which reads a text file (which contains absolute paths of many files one below the other), calculates the file names from abs path & then appends all file names separated by a space to the same file. So, consider a test.txt file:

D:\work\project\temp.txt
D:\work/tests/test.abc
C:/office/work/files.xyz

So after running the script the same file will contain:

D:\work\project\temp.txt
D:\work/tests/test.abc
C:/office/work/files.xyz

temp.txt test.abc files.xyz

I have this script revert.pl:

use strict;

foreach my $arg (@ARGV)
{
    open my $file_handle, '>>', $arg or die "\nError trying to open the file $arg : $!";
    print "Opened File : $arg\n";
    my @lines = <$file_handle>;
    my $all_names = "";

    foreach my $line (@lines)
    {
        my @paths = split(/\\|\//, $line);
        my $last = @paths;
        $last = $last - 1;
        my $name = $paths[$last];
        $all_names = "$all_names $name";
    }

    print $file_handle "\n\n$all_names";
    close $file_handle;
}

When I run the script I am getting the following error:

>> perl ..\revert.pl .\test.txt
Too many arguments for open at ..\revert.pl line 5, near "$arg or"
Execution of ..\revert.pl aborted due to compilation errors.

What is wrong over here?

UPDATE: The problem is that we are using a very old version of perl. So changed the code to:

use strict;

for my $arg (@ARGV)
{
print "$arg\n";
open (FH, ">>$arg") or die "\nError trying to open the file $arg : $!";
print "Opened File : $arg\n";
my $all_names = "";
my $line = "";

for $line (<FH>)
{
    print "$line\n";
    my @paths = split(/\\|\//, $line);
    my $last = @paths;
    $last = $last - 1;
    my $name = $paths[$last];
    $all_names = "$all_names $name";
}
print "$line\n";

if ($all_names == "")
{
    print "Could not detect any file name.\n";
}
else
{
    print FH "\n\n$all_names";
    print "Success!\n";
}
close FH;
}

Now its printing the following:

>> perl ..\revert.pl .\test.txt
.\test.txt
Opened File : .\test.txt

Could not detect any file name.

What could be wrong now?

Upvotes: 1

Views: 1082

Answers (1)

Miguel Prz
Miguel Prz

Reputation: 13792

Perhaps you are running an old perl version, so you have to use the 2 params open version:

open(File_handle, ">>$arg") or die "\nError trying to open the file $arg : $!";

note I wrote File_handle without the $. Also, read and writting operations to the file will be:

@lines = <File_handle>;
#...
print File_handle "\n\n$all_names";
#...
close File_handle;

Update: reading file lines:

open FH, "+>>$arg" or die "open file error: $!";
#...
while( $line = <FH> ) {
   #...
}

Upvotes: 1

Related Questions