|
-
Oct 16th, 2001, 06:02 AM
#1
Thread Starter
Addicted Member
perl script: Read and Write problem
I am trying to write a simple perl script which opens a file called file1.txt, reads the first 3 lines, and writes them to another file called output.txt
Can someone show me how to do this ? So far I have written the following:
#!/usr/bin/perl
# test.pl
use warnings;
use strict;
my $infile = "file1.txt";
my $outfile = "output.txt";
open FILE, $infile or die $!;
???
-
Oct 16th, 2001, 06:49 AM
#2
Black Cat
Code:
#open the out put file
open (OUTFILE, ">$outfile") or die "Couldn't open outfile: $!\n\n";
#for every line in the input file, write to the output file
while (<INFILE>) {
print OUTFILE;
}
#don't forget to close the file handles
close (INFILE);
close (OUTFILE);
Josh
Get these: Mozilla Opera OpenBSD
I have books for sale: "MCSD in a Nutshell" and "VB Distributed Exam Cram" - PM me for details. Will also trade for a decent ATX Pentium 2 MB/CPU/RAM combo.
-
Oct 16th, 2001, 09:02 AM
#3
Thread Starter
Addicted Member
thanks josh
can i ask another question:
When I read my infile I want to ignore the first several records until I get to a record which reads BBH. I want to read all the records from BBH up until a record which reads PPH and store these values into variables.
Can you point me in the right direction please. Do I use a While Loop or Loop Until ?
-
Oct 16th, 2001, 10:58 AM
#4
Black Cat
How is your text file formatted? You can use regular expressions to look for and match the BBH or PPH. I think the type of loop to use is mostly a matter of the programmer's preference.
Josh
Get these: Mozilla Opera OpenBSD
I have books for sale: "MCSD in a Nutshell" and "VB Distributed Exam Cram" - PM me for details. Will also trade for a decent ATX Pentium 2 MB/CPU/RAM combo.
-
Oct 16th, 2001, 11:09 AM
#5
Thread Starter
Addicted Member
The file is formatted as follows:
AAH
BBH
SST
PTR
GGH
PPH
etc..
-
Oct 16th, 2001, 11:59 AM
#6
Frenzied Member
As Josh said, the loop you use is a matter of prefference. You can rewrite every loop in a different style. I tend to use for/foreach loops.
Code:
foreach $line (<INFILE>) {
if (m/^BBH/) {
#Do magic
}
}
Mind you, it has been a few months since I did any Perl, so there may be gross syntax problems, but the idea is sound. Check the Camel book and the Cookbook. They are the holy tomes of Perl.
Travis, Kung Foo Journeyman
As always, RTFM.
WWW Standards: HTML 4.01, CSS Level 2, ECMA 262 Bindings to DOM Level 1, JavaScript 1.3 Guide and Reference
Perl: Learn Perl, Llama, Camel, Cookbook, Perl Monks, Perl Mongers, O'Reilly's Perl.com, ActiveState, CPAN, TPJ, and use Perl;
YBMS, but Mozilla doesn't.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|