Home arrow Perl Programming arrow Page 3 - Perl: Appending and Writing to Files

Overwriting Without Deleting Everything - Perl

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.

TABLE OF CONTENTS:
  1. Perl: Appending and Writing to Files
  2. Writing to Files
  3. Overwriting Without Deleting Everything
  4. How to Delete a File
  5. More Ways to Test Files
By: James Payne
Rating: starstarstarstarstar / 9
November 14, 2007

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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



 
 
>>> More Perl Programming Articles          >>> More By James Payne
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PERL PROGRAMMING ARTICLES

- Perl Turns 25
- Lists and Arguments in Perl
- Variables and Arguments in Perl
- Understanding Scope and Packages in Perl
- Arguments and Return Values in Perl
- Invoking Perl Subroutines and Functions
- Subroutines and Functions in Perl
- Perl Basics: Writing and Debugging Programs
- Structure and Statements in Perl
- First Steps in Perl
- Completing Regular Expression Basics
- Modifiers, Boundaries, and Regular Expressio...
- Quantifiers and Other Regular Expression Bas...
- Parsing and Regular Expression Basics
- Hash Functions

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: