-1

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.

shreyaskar
  • 375
  • 1
  • 3
  • 14
  • 3
    Change `die("Cannot open file")` to `die("Cannot open file ($!)")` and post the error message that is showed after the change. – sticky bit Mar 11 '20 at 11:54
  • ```$ perl perlRedirect.pl 10 Hello! Cannot open file (Permission denied) at perlRedirect.pl line 14. ``` The error message after the change – shreyaskar Mar 11 '20 at 11:58
  • 6
    That reveals that you (or rather the user the program runs under) has no right to either open the file (in write mode) or create it. Check the permissions of the file and/or the directory that should contain it. – sticky bit Mar 11 '20 at 12:00
  • 1
    It is more conventional to include the path in the error message. eg `open my $fh, ">", $filepath or die "$filepath: $!";` – William Pursell Mar 11 '20 at 12:57
  • How can I grant permissions within this script? @stickybit – shreyaskar Mar 11 '20 at 14:51
  • @Shreyaskar: You would change the file's permissions with the [chmod](https://perldoc.perl.org/functions/chmod.html) function. But if you don't have permission to write to the file, you might not have permission to change its permissions. – Dave Cross Mar 11 '20 at 15:29
  • @DaveCross: Is there any alternative to this? – shreyaskar Mar 12 '20 at 05:43
  • @Shreyaskar: You find the person who owns the file and ask them to change the permissions for you. – Dave Cross Mar 12 '20 at 07:57

1 Answers1

0

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!

shreyaskar
  • 375
  • 1
  • 3
  • 14