Coplan has asked for the wisdom of the Perl Monks concerning the following question:

I have this really bizarre idea about creating a script that can (among many other things) maintain itself and clean itself up. As part of the script, I'd like the script to examine itself and, if necessary, change itself. Obviously, dealing with problems of file access can easily corrupt a program. So i'm stumped as to how to go about doing this.

I have two thoughts as to how this might be done:

1) The script either runs as a copy, or creates a copy of itself and examines the file that is not currently being accessed. If necessary, make changes the the accessible copy and, when finished, the script closes itself and runs the new version of the script (and delete the old version).

2) Load and run the script in memory so that there's no file access violations on the original file, and whenever a change is made, that file is updated. When the script is complete, you will be left with an up-to-date file as a result of the scripts own changes.

Are either of these options possible? Or am I getting into something that is beyond the limitations of Perl? I just think that the possibilities of such a method would be endless.

FYI, I'm using a Redhat Linux OS.

--Coplan

Replies are listed 'Best First'.
Re: Run as copy or read/write self
by broquaint (Abbot) on May 14, 2003 at 17:20 UTC
    Why these are the very principles which powers TheDamian's minion selfGOL (well those and pure unrelenting evil ;) If you've got your permissions setup correctly then to change your script within the script can just be a simple combination of open and exec e.g
    print "am in $0\n"; { local $/; seek DATA, 0, 0; (my $data = <DATA>) =~ s/\bexec\b.*\n//; open(ME, ">$0") or die("ack - $!"); print ME qq[print "am in new \$0\\n";\n], $data; close ME; } exec "perl $0"; __DATA__

    HTH

    _________
    broquaint

Re: Run as copy or read/write self
by halley (Prior) on May 14, 2003 at 17:08 UTC

    It should be really straightforward to do. You're almost describing a quine. Try running spiraling quine for one (not-so-obvious) approach. My own quine is the Pentominos Solving Quine.

    One common method that quines in Perl often use is to rewind the DATA handle or the 0 handle, which can read the script's own source code as data. If you want it to invoke the new version, see the exec() built-in function.

    --
    [ e d @ h a l l e y . c c ]