In our last tutorial we left off on the topic of creating files and manipulating the data therein. In this article we will discuss how to append to a file and how to write to a file. If there is time, we will also discuss working with file checks.
Okay, so maybe we were a little hasty in overwriting the entire table. To be fair, there is not a way to delete a single line of data with the Overwrite command. But we can trick the program using our gigantic brains. For this example we are going to work with our original four sets of data. We are going to delete Daredevil (our second record it seems) from the table. Observe!
$my_file="superhero.txt";
open(PLOT, $my_file) || die('Oops the file is broked!');
@my_data=<PLOT> ; #stores the data from the file in an array called @my_data
close(PLOT);
splice(@my_data,1,1);
open(PLOT,">$my_file") || die("File won't open");
print PLOT @my_data;
close(PLOT);
The splice command works by look at the command and removing the array element you indicate (1,1...remember arrays start at the number 0. Since daredevil is the second element, we use 1).
When you are finished, this is the data that will remain in the file:
The Incredible Hulk|Super Strength|I rip my pants
Apache Chief|the ability to grow Very Tall|I Wear a skirt
Aqua Man|the ability to communicate with fish|deep fryers and tartar sauce