Home arrow Perl Programming arrow Page 3 - Perl 101 (Part 4) - Mind Games

Different Strokes - Perl

This week's article teaches you how to use Perl to interact withfiles on your system, and also provides you with a quick crash course invarious array functions.

TABLE OF CONTENTS:
  1. Perl 101 (Part 4) - Mind Games
  2. Handle With Care
  3. Different Strokes
  4. A Little Brainwashing
  5. Die! Die! Die!
  6. Testing Times
  7. Popguns And Pushpins
  8. Shifting Things Around
  9. The Real World
  10. Miscellaneous Stuff
By: Vikram Vaswani and Harish Kamath, (c) Melonfire
Rating: starstarstarstarstar / 11
June 29, 2000

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement
There's also another method of reading data from a file - a loop that will run through the file, printing one line after another:
#!/usr/bin/perl
# open file and define a handle for it
open(MIND,"thoughts.txt");
# assign the first line to a variable
$line = <MIND>;
# use a loop to keep reading the file
# until it reaches the end
while ($line ne "")
{
print $line;
$line = <MIND>;
}
# close file when done
close(MIND);
# display message when done
print "Done!\n";

Well, it works - but how about making it a little more efficient? Instead of reading a file line by line, Perl also allows you to suck the entire thing straight into your program via an array variable - much faster, and definitely more likely to impress the girls!

Here's how:
#!/usr/bin/perl
#pen file and define a handle for it
open(MIND,"thoughts.txt");
# suck the file into an array
@file = <MIND>;
# close file when done
close(MIND);
# use a loop to keep reading the file
# until it reaches the end
foreach $line (@file)
{
print $line;
}
# display message when done
print "Done!\n";

As you can see, we've assigned the contents of the file "thoughts.txt" to the array variable @file via the file handle. Each element of the array variable now corresponds to a single line from the file. Once this has been done, it's a simple matter to run through the array and display its contents with the "foreach" loop.

This article copyright Melonfire 2000. All rights reserved.

 
 
>>> More Perl Programming Articles          >>> More By Vikram Vaswani and Harish Kamath, (c) Melonfire
 

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: