in reply to Perl File Editing Subroutines, Any ideas?
Slurp the file, edit the lines, write the file back out:
use strict; use warnings; my @edits = ( delete => ['my'], delete => ['open'], delete => ['rename'], delete => ['{'], delete => ['}'], delete => ['^\\s*$'], delete => ['\\$_'], replace => ['use.*;', '# Strictures are really important'], ); edit ('noname.txt', @edits); sub edit { my ($file, @edits) = @_; my $old = $file; # Old file my $new = "$file.tmp.$$"; #New File to create my $bak = "$file.bak"; #backup of old file my %dispatch = ( insert => \&insert_line, delete => \&delete_line, replace => \&search_replace, ); $old = $file; $new = "$file.tmp.$$"; $bak = "$file.bak"; open my $OLD, '<', $old or die "Can't open $old: $!"; my $inLines; @$inLines = <$OLD>; close ($OLD); while (@edits >= 2) { my ($edit, $params) = splice @edits, 0, 2; my $outLines = []; next unless exists $dispatch{$edit}; $dispatch{$edit}->($inLines, $outLines, @$params); $inLines = $outLines; } open my $NEW, '>', $new or die "Can't open $new: $!"; print $NEW @$inLines; close ($NEW); rename ($old, $bak); rename ($new, $old); } sub insert_line { my ($in, $out, $after, $insertline) = @_; for (@$in) { $_ .= $insertline if /$after/; push @$out, $_; } } sub search_replace { my ($in, $out, $find, $replace) = @_; for (@$in) { s/$find/$replace/g; push @$out, $_; } } sub delete_line { my ($in, $out, $delete) = @_; for (@$in) { push @$out, $_ unless /$delete/; } }
run against itself generates:
# Strictures are really important # Strictures are really important replace => ['# Strictures are really important', '# Strictures are + really important'], ); edit ('noname.txt', @edits); insert => \&insert_line, delete => \&delete_line, replace => \&search_replace, ); $old = $file; $new = "$file.tmp.$$"; $bak = "$file.bak"; @$inLines = <$OLD>; close ($OLD); $inLines = $outLines; print $NEW @$inLines; close ($NEW); s/$find/$replace/g;
|
|---|