Perl Write to File

open(my $fh, '>', 'report.txt');
print $fh "My first report generated by perl\n";
close $fh;
# no package/library needed/dependant

This is a simple Perl script to write a string to a file named “report.txt”. Here’s a step-by-step explanation:

  1. open(my $fh, '>', 'report.txt'): The open function is used to open a file for writing. The first argument, my $fh, is a filehandle, which is used as a reference to the file. The second argument, '>', specifies that the file should be opened for writing, overwriting any existing data. The third argument, 'report.txt', is the name of the file.
  2. print $fh "My first report generated by perl\n": The print function writes a string to the file. The first argument, $fh, specifies the filehandle. The string to be written is "My first report generated by perl\n". The newline character \n is used to ensure that the string is written on a new line.
  3. close $fh: The close function is used to close the file. The argument $fh specifies the filehandle.

Note: No additional packages or libraries are needed for this code to work.