|
Posted by smallpond on June 17, 2008, 2:56 pm
Please log in for more thread options n_macpherson@sky.com wrote:
> I know there are a number of FAQs which disscourage reading whole
> files into memory rather than line by line.
>
> However my problem is as follows.
>
> I am reading a file which is a language which looks like (but isn't )
> C. I need to insert comments / documentation at various points in the
> file. However sometimes I don't know what I want to insert until I get
> well past the current line - for example
>
>
> for(i=0;i<64;i++)
> {
> // lots of code
> }
>
> Say my opening brace is on line 95 and my closing brace 195 I want to
> insert a comment
>
> // for loop ends line 195
>
> at line 94 (i.e immediately above the opening brace). The problem is
> that processing line by line I don't know until I get to line 195 what
> I have to change at line 9 so I have to store lines 94 to 195 in
> memory anyway
>
> Similarly if I read a function header, I want to insert some
> documentation before the function header
> so I don't believe processing the file line by line is the best
> solution here. As I will be inserting extra lines into the middle of
> an array I think I am going to need a module to do this.
>
> Memory won't be an issue - my largest file will only be 6000
>
> I've been away from Perl for a while but I seem to remember there was
> a module File::Tie which might be suitable.
>
> I'd be grateful if anyone has any suggestions - the people who will be
> using this don't normally use Perl so I'd like to avoid using any non-
> standard modules if possible
>
> Thanks
>
> Niall
1) Read the file into an array of lines.
2) Build a hash of your inserts, key=line number.
3) Write out the updated file inserting each new line as you get to it.
This way you don't have to modify the array which would change the
line indices.
** Posted from http://www.teranews.com **
|