add a 3 lines of text in a file before "package" in file

M

mike

Hi,

I am using perl and need to add some text lines before the word
"package" in the file. I have read about Tie::File
and I am trying to use it as below. But I am unable to see how I can
match the word "package" and add
/* ---- Insert text here ---- */
on the line before "package".

Any ideas?

//mike

sub modify {
my @line_array;
my $line;
my ($file) = @_;
print "Modifying file, $file\n";
tie @line_array, 'Tie::File', $file or die "Can not tie file:$!";
for $line(@line_array) {
//
}
untie @line_array;

}
 
U

Uri Guttman

BM> Is the file likely to be large (which probably means several hundred MB,
BM> nowadays)? If not, it would be easier to use File::Slurp and do a simple
BM> s/// on the whole file before writing it out again.


yes, slurping is fine for many megabytes today which is something people
have to learn. text files have not grown like ram sizes have (other than
biogen and similar stuff). slurping this is easy and fast:

(untested)

use File::Slurp ;

my $text = read_file( $file ) ;
$text =~ s{(^.*package.*$)}
{/* ---- Insert text here ---- */\n$1}m ;
write_file( $file, $text ) ;

uri
 
J

John W. Krahn

mike said:
I am using perl and need to add some text lines before the word
"package" in the file.

$ echo "one
two
three
four package
five
six" | perl -pe'/package/&&print "new text 1\nnew text 2\nnew text 2\n"'
one
two
three
new text 1
new text 2
new text 2
four package
five
six



John
 
X

Xho Jingleheimerschmidt

Ben said:
This will read the entire file to count the lines before it starts,
removing any benefit of using Tie::File.

That is far from the only benefit of Tie::File. I don't think it is
even one of the benefits of Tie::File to start with. Not that I think
that Tie::File has all that many benefits to start with. One of the
benefits it does have is letting you write into the middle of a file in
a way that syntactically and logically easy, though quite inefficient.
This benefit is maintained, and ISTM is the whole point.

Xho
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top