Search code examples
fileperlfile-permissionsfile-handlingfilehandle

Perl script unable to open a file in write mode


As I am new to Perl can anyone help me out with this code. I want to write contents to a file named redirectedOutputFile (create one such file if it does not exist).

perlRedirect.pl

$var = @ARGV[0];

print "Hello!\n";


$filepath = "/tools/<some_location>/testdir1/redirectedOutputFile";
open(FILE_HANDLE, ">", $filepath) or die("$filepath: $!");

#system("chmod 777 redirectedOutputFile");
print FILE_HANDLE "Permissions given!\n";

foreach(1..$var){
    #print "Hi!\t";
    print FILE_HANDLE "$_\n";

}

print FILE_HANDLE "Done!\n";

When I execute the script using $ perl perlRedirect.pl 10

I am getting the output :

/tools/<some_location>/testdir1/redirectedOutputFile: Permission denied at perlRedirect.pl line 14. 

I want the script to create a new file if it does not exist and store the contents in the same file. Also, can I change permissions of redirectedOutputFile in this script? Thank you.


Solution

  • I tried running the script with the help of sudo and it works fine!

    I changed the execution line to sudo perl perlRedirect.pl 5

    With this I got the output as: Hello!