Home arrow Perl Programming arrow Page 4 - Perl: Working with Files

Manipulating Data - Perl

In our last series of tutorials we worked with Conditionals and Loops to create some basic Perl programs. This time around we are going to be working with files. Text files, CGI files, PL files, boiled files, fried files, Files Benedict, steamed Files. Okay, so I was kidding about the steamed Files.

TABLE OF CONTENTS:
  1. Perl: Working with Files
  2. How to Open a File
  3. How to Read a File
  4. Manipulating Data
  5. How the Code Works
By: James Payne
Rating: starstarstarstarstar / 8
November 07, 2007

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Now that we have read the contents of our file, let's put that lazy, good for nothing data to work. As you may or may not have guessed, our table of data consists of super hero names, their super powers, and their weaknesses. So for instance, the Indian super hero Apache Chief has the ability to grow tall; unfortunately he also wears a man-skirt, and people can see under it when he does, which is a weakness. Similarly, the Incredible Hulk transforms in a super strong behemoth, but when he does so, his pants explode. I mean, talk about a weakness. The guy has to buy new pants every time he gets angry.

Let's create a program that utilizes all of the data in the file:


#!/usr/bin/perl


$my_file=”super.txt”;


open(PLOT, $my_file) || die(“I refuse to open your file!”);

@my_data=<PLOT>;

close(PLOT);


print “Content-type: text/html\n”;

print “<HTML><BODY>”;


foreach $superhero (@my_data)


{

chop($superhero);

($hero_name, $hero_power, $hero_weakness)=split(/\|/,$superhero);

print “My name is $hero_name, my super power is $hero_power, and my weakness is $hero_weakness. I hate my life.”;

print “<BR>\n\n"

}


print “</BODY></HTML>”;



The above code will print out the text:

  My name is The Incredible Hulk, my super power is Super Strength, and my   weakness is I rip my pants

  My name is Daredevil, my super power is heightened senses, and my weakness is I have poor fashion sense due to blindness

  My name is Apache Chief, my super power is the ability to grow very tall, and my weakness is I wear a skirt



 
 
>>> 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: