Hallo Gast,
bitte verwende
use strict; und
use warnings; in deinem Code!
Bitte prüfe auch den Returnwert von open():
open(input, "<input.inp") or die "unable to open input.inp: $!";
Die Verwendung einer lexikalischen Variable ist vorzuziehen:
open(my $FH, "<input.inp") or die ...
Wenn die Datei sehr klein ist, dann könnte man es eventuell so lösen wie
du es vorhast, allerdings dann nicht mit @lines sondern mit $lines und der
Regex fehlt noch ein wenig. Bei größeren Dateien könnte man es so lösen:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
use strict;
use warnings;
use Fcntl qw/O_RDONLY O_WRONLY O_CREAT O_EXCL/;
my $cur_file = 'foo.txt';
my $tmp_file = 'foo.txt.tmp';
sysopen my $in, $cur_file, O_RDONLY or die "unable to open foo.txt: $!";
sysopen my $out, $tmp_file, O_WRONLY | O_EXCL | O_CREAT or die "unable to open foo.txt.tmp: $!";
my $start_pos;
my $replacement = "Hello World\n";
while (my $line = <$in>) {
print $out $line;
if ($line =~ /^test$/) {
my $hit = 0;
$start_pos = tell($in);
while (my $line = <$in>) {
if ($line =~ /^test2$/) {
$hit++;
print $out $replacement;
print $out $line;
last;
}
}
unless ($hit) {
seek($in, $start_pos, 0);
}
}
}
close $in;
close $out;
rename($tmp_file, $cur_file)
or die "unable to rename $tmp_file to $cur_file";
What is a good module? That's hard to say.
What is good code? That's also hard to say.
One man's Thing of Beauty is another's man's Evil Hack.