Re: Reading whole file with while(INPUT) but I need to access each line
- From: "Marcel" <downloads666@xxxxxxxxxxx>
- Date: 31 Aug 2006 08:02:30 -0700
Hi Hamish
I think what you are looking might be Tie::File
http://search.cpan.org/~mjd/Tie-File-0.96/lib/Tie/File.pm
This way you don't have to read the file into memory, but can still
work on it as if it was an array.
Hope that helps,
Marcel
HAMISH wrote:
Hi perl hackers
Previously I was reading a file a line at a time
@lines = <input>
It was then pointed out that the FAQ has a better way of reading files.
This is with
open (INPUT, $file) || die "can't open $file: $!";
while (<INPUT>) {
chomp;
# do something with $_
}
close(INPUT) || die "can't close $file: $!";
However I need to change every line that is read. I also have to
sometimes add lines together based on a certain condtion so maybe 4
lines need to be turned into 1. I have a C background so I chose to
use a for loop so i can access different elements. Here is an example
of my code without all the file reads etc. I have put an example in an
array.
The example input from the C file
if( ( A) || ( B)
||()
||()
||()
{
CODE EXAMPLE
----------------------------------------------------------------------
#!/usr/bin/perl
use warnings;
use strict;
my @lines;
my $lines;
my $i;
my $j;
@lines = ("if( ( A) || ( B) \n", "||() \n", "||() \n", "||() \n",
"||()) \n", "{" );
for( $i = 0 ; $i < scalar @lines ; $i++)
{
chomp @lines;
if( $lines[$i] =~ /\)$/ )
{
$j = 1;
while ($lines[$i+$j] =~ /^\|\|/ ) # if line starts with || add it to
the previous line
{
$lines[$i] = $lines[$i]." ".$lines[$i+$j];
$j++;
}
}
unless ( $lines[$i] =~ /^\|\|/ ) #skip lines that start with || so
they dont get printed twice
{
print $lines[$i]."\n";
}
}
This comes out with the right result. It might be lucky but I have
tested it with a few examples of what might come up.
Now my question is.. How would I do this using the input file Code from
the Faq? Because in that case I would not have an array of lines. Is
there a way this can be done or do I need to create the array of lines?
The input files are C code so I want to create code that joins expanded
If statements that may go over as many as 5 lines.
after I have worked this out I will apply the same code for all extened
expressions that go over multiple lines.
.
- References:
- Prev by Date: File locking issue
- Next by Date: Re: Trouble with variable scoping
- Previous by thread: Reading whole file with while(INPUT) but I need to access each line
- Next by thread: Trouble with variable scoping
- Index(es):
Relevant Pages
|