Martin Spinassi wrote:
Hi list!
Hello,
I've just started with perl, but I'm really excited about its power.
I'm excited that you're excited! ;-)
I'm trying to edit a file, but couldn't find out how to do it without
making a temp file. I've been searching for the solution, but all I find
is how to do it from command line, adding a "-i" to the execution.
My script dump some database structures to files, each file for each
table, and then I want to edit those files, but couldn't make the
edition infile, and do not want to duplicate files for just editing them
(using $^I).
Is there any way to open a file for input and output at the same time?
perldoc -f open
[ snip ]
You can put a '+' in front of the '>' or '<' to indicate that
you want both read and write access to the file; thus '+<' is
almost always preferred for read/write updates--the '+>' mode
would clobber the file first. You can’t usually use either
read-write mode for updating textfiles, since they have variable
length records. See the -i switch in perlrun for a better
approach. The file is created with permissions of 0666 modified
by the process’ "umask" value.
This is just and example, and doesn't work, but may be it explains
better what I'm trying to do:
while (glob "*.dump") { #I know there is not a "<>"
open (TMPFILE,"<&>", $_) or die "Could not open file $_: $!\n";
while (<TMPFILE>) {
s/^--.*//;
print;
}
}
Your best bet is probably to read the entire file into memory, modify
it, and then write it back out. Something like this (UNTESTED):
use Fcntl ':seek';
while ( my $file = glob '*.dump' ) {
open my $TMPFILE, '+<', $file or die "Could not open file $file: $!\n";
local $/;
my $data = <$TMPFILE>;
$data =~ s/^--.*//gm;
seek $TMPFILE, 0, SEEK_SET or die "Could not seek file $file: $!\n";
print $TMPFILE $data;
truncate $TMPFILE, length $data;
}
Other methods would include using Tie::File or one of the mmap modules.
For example:
use Tie::File;
while ( my $file = glob '*.dump' ) {
tie my @data, 'Tie::File', $file or die "Could not open file $file:
$!\n";
s/^--.*// for @data;
untie @data;
}
John
--
Those people who think they know everything are a great
annoyance to those of us who do. -- Isaac Asimov
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/