Search code examples
perl

Can a Perl script modify itself?


I would like to have my scripts keep track of thier last date of revision internally as a comment. Is this possible? It seems to me that it would need to grab the date and then open its script file for an append, write the data and save the file.

Thanks Everone, great answsers one and all. Based on the code snippet left by GreenMatt I threw this together...

#!/usr/bin/perl -w 

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime time;
$year += 1900;
$mon +=1;

open SELF, ">> letterhome.pl" or die "Unable to open self"; 
#print SELF "# ran/modified at " . join(' ', localtime(time)) . "\n"; 
print SELF "# ran/modified at $hour:$min:$sec on $mon/$mday/$year.\n"; 
close(SELF); 

# ran/modified at 31 48 23 24 7 110 2 235 1  
# unformated result of using localtime(time)  

#Results using formated time/date 
# ran/modified at 0:1:43 on 8/25/2010.
# ran/modified at 0:2:40 on 8/25/2010.
# ran/modified at 0:4:35 on 8/25/2010.

Solution

  • It is possible, but that doesn't make it a good idea. For one thing, it wouldn't update the date until you ran it.

    If you're using a good editor, it may have a way to insert a timestamp automatically when you save the file. For example, I set up Emacs to do that in HTML files using write-contents-hooks. (It would need some modification to work with Perl code, but cjm-html-timestamp in cjm-misc.el would give you a starting point.)