in reply to can a script change itself?

There are better ways of doing this, but yes, a script can change itself. Here is a self modifying script that keeps track of the number of times it is called.
# Get current file name $filename = __FILE__; # get old UID stored after __END__ $uid = <DATA>; chomp($uid); print "This script has been run $uid times $/"; # increment UID $uid++; # open current running file open(THIS_IN, $filename) or die "Could not open file"; @code = <THIS_IN>; close (THIS_IN); # Store new UID in last line of this code $size = @code; @code[$size-1]=$uid; # open current running file open(THIS_OUT,"> $filename") or die "Could not output to file"; print THIS_OUT @code; close (THIS_OUT); __END__ 0
This is presented mostly for interest, as I am from the school of thought that self-modification is bad. It can lead to some very hard to track down bugs.

Replies are listed 'Best First'.
Re: A script can change itself
by CountZero (Bishop) on Mar 24, 2005 at 20:26 UTC
    The idea is great and it works nicely, but only if you are sure that you are the only user of this script. It will not work in a web-server environment or --heaven forbid-- in a mod_perl environment for instance where this same script could be called by more than one client at the same time as it has no protection against such classical race conditions.

    I know "multiple concurrent user safety" wasn't part of the specs of this question, but I thought it would be good to give a word of warning here anyhow. I've been bitten before by race conditions when using cook-book (aka cut-and-paste) style programming before.

    CountZero

    "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law

      I know "multiple concurrent user safety" wasn't part of the specs of this question, but I thought it would be good to give a word of warning here anyhow. I've been bitten before by race conditions when using cook-book (aka cut-and-paste) style programming before.

      I learned one lesson in my intro to concurrency course: "Concurrency is hard." There are few, if any, concurrent debuggers in existance ( one grad student was working on one, with some limited success), and the very convenient rule that states "if I run the same program, with the same inputs, I'll get the same output" goes out the window, because other programs can interfere.

      Avoid concurent programs when you can: when you can't, swear loudly and quadruple your delivery date.
      --
      Ytrew