Writing to Files

Copy the text of the script and run it in Perl. You'll have to reset the name of "test.txt" to a file in the same directory of your script, or you won't see any output.

# writeFile1.pl

# program opens a file, reads it, and prints
# the content to STDOUT and output file

# first, create a variable that holds the path to the source file

$source = "test.txt"; # assuming the file is in the same dir as the script

# second, create a variable that holds the path the output file

$target = "testOut.txt"; # creates the file in the same dir as the script


# third, create filehandles named 'SOURCE' and 'TARGET';
# TARGET is the output file; we have to specify whether
# we want the overwrite the file    ==> (">$target")
# or append to the end of the file  ==> (">>$target")

open(SOURCE, "<$source");  #  <  is optional for reading files
open(TARGET, ">$target");  #  >  overwrites existing file
                           #  >> appends to existing file

# get input from SOURCE
while (<SOURCE>)
{
     # we have two output filehandles, STDOUT and TARGET;
     # STDOUT is default, so 'print' will go to STDOUT;
     # to put output to TARGET, we have to specify
     # 'print TARGET'

     print STDOUT $_;
     print TARGET $_;
    
}
print "\n\n";
close(SOURCE);  # for good measure
close(TARGET);