Last active
March 7, 2020 22:02
-
-
Save saiftynet/0f442ec13d421a9a130f3b39334065ae to your computer and use it in GitHub Desktop.
self modifying perl code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/env perl | |
use strict;use warnings; | |
my %config; | |
loadConfig(); ##load config from __DATA__ | |
foreach (sort keys %config){ | |
print $_, " => ",$config{$_},"\n__\n";# display config | |
print "Enter new Value for $_\n>>"; # offer to modify it | |
chomp( $config{$_}=<>); # modify it | |
} | |
saveConfig(); #save new config | |
sub loadConfig{ # read keys and values from data | |
my ($key, $value); | |
while (my $line = <DATA>){ | |
if ($line=~/\[([^\]]+)\]/){ | |
$key=$1; | |
} | |
elsif($key and $line!~/^\s*$/){ | |
$config{$key}.=$line; | |
} | |
}; | |
foreach (keys %config){ | |
$config{$_}=~s/\s*$//g; | |
} | |
} | |
sub saveConfig{ # save config into data segment | |
open my $readFile, '<', $0 or die "can't open $0: $!"; | |
open my $tempFile, '>', $0.".tmp" or die "can't open $0.tmp: $!"; | |
while (<$readFile>){ # read own code | |
last if $_=~/^__DATA__/; # store everithing upto the data | |
print $tempFile $_ # segment into a temporary file | |
}; | |
close $readFile; | |
print $tempFile "__DATA__\n"; # now create a new __DATA__ segment | |
foreach (sort keys %config){ # store everything from config | |
print $tempFile "[$_]\n$config{$_}\n\n"; | |
} | |
close $tempFile; | |
unlink "$0.bak"; # delete previous backups | |
rename $0, "$0.bak"; # backup current file | |
rename "$0.tmp", $0; # make temp the new code | |
} | |
__DATA__ | |
[bestFriend] | |
gertie | |
[birthDate] | |
12-12-12 | |
[description] | |
not much is known, but likes blue, has gertie for a best friend and is 7 | |
[favouriteColour] | |
blue | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment