Monday, July 23, 2007

Scripting woes

I was trying to get a perl script with a sed oneliner called from within the perl script..
It started itching me when I tried inserting a few leading spaces into the replacement text in sed.
Here's the snippet

my $mask = '255.255.255.0';
foreach my $device (sort keys %ifaddrs) {
unless ($ifmasks{$device}) {
$t = `sed -e "/255.255/ a\ \\\t '$device' => '$mask'," $deffile > $deffile.new ` ;
print $t ;

The leading tab never worked properly till we finally preceded \t with two escape sequences- one each for the perl and sed parsing.
With the third one , it finally worked. The better part of it was that the perl variables worked well in sed ..i.e. they were parsed by perl before passing it on to sed..well, in another way thats what screwed me when it came to the white spaces..Anyway all working now, here's the full script...
#!/usr/bin/perl
#use strict;
use warnings;
my $file = shift @ARGV;
my $check = 0;
print "\nchecking $file\n";
check_arrays($file);
sub check_arrays {
my $deffile = shift;
#my (%ifaddrs, %ifmasks, %bootproto, %onboot);
require "$deffile";
my $mask = '255.255.255.0';
foreach my $device (sort keys %ifaddrs) {
unless ($ifmasks{$device}) {
print "$deffile def file does not have ifmasks for $device\n";
$t = `sed -e "/255.255/ a\ \\\t '$device' => '$mask'," $deffile > $deffile.new ` ;
print $t ;
}
unless ($bootproto{$device}) {
print "$deffile def file does not have bootproto for $device\n";
}
unless ($onboot{$device}) {
print "$deffile def file does not have onboot for $device\n";
}
}
undef %ifaddrs;
undef %ifmasks;
undef %bootproto;
undef %onboot;
}

No comments: