in reply to Update config file parameters
You can do inplace editing of files:
use strict; use warnings; use 5.020; my %new_values = ( ONBOOT => 'no', TYPE => 'Wifi', ); my $file_name = "data.txt"; read_file($file_name, \%new_values); sub read_file { my ($fname, $new_values_href) = @_; local $^I = ".bak"; #Enable inplace editing for this block only. local @ARGV = $fname; #Set value for @ARGV for this block only. while (my $line = <>) { my ($name, $val) = split /=/, $line; my $replacement_value = $new_values_href->{$name}; if (defined $replacement_value) { say "$name=$replacement_value"; #Output goes to file } else { print $line; #Output goes to file } } } #Restore $^I and @ARGV to the values they had before the block
To get inplace editing, you cannot read a file like this:
while(my $line = $INFILE)
You have to read a file using the diamond operator: <>. You cannot have anything between the angle brackets. The diamond operator reads from @ARGV (or STDIN if @ARGV is empty). So, you either have to set @ARGV to the file name, or enter the file name on the command line. @ARGV contains all the arguments entered on the command line.
When you enable inplace editing, perl creates a new file, redirects STDOUT to the new file, i.e. print() and say() go to the new file; and when you are done, perl saves a copy of the original file using the original file name with a .bak extension, then perl renames the new file to the original file name. If you don't want to save a copy of the original file, then write:
{ local $^I = ""; ... ... }
Here's a sample run:
~/pperl_programs$ cat data.txt DEVICE=eth0 ONBOOT=yes BOOTPROTO=static TYPE=Ethernet IPADDR=10.9.0.200 NETMASK=255.255.0.0 GATEWAY=10.9.1.254 ~/pperl_programs$ perl 1.pl ~/pperl_programs$ cat data.txt DEVICE=eth0 ONBOOT=no BOOTPROTO=static TYPE=Wifi IPADDR=10.9.0.200 NETMASK=255.255.0.0 GATEWAY=10.9.1.254
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Update config file parameters
by afoken (Chancellor) on Jan 07, 2016 at 21:38 UTC |