Can a Perl script modify itself?

前端 未结 6 1449
旧巷少年郎
旧巷少年郎 2020-12-31 10:48

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

相关标签:
6条回答
  • 2020-12-31 11:24

    You can get your version control system to do this automatically.

    But if you are using version control then this step is really not nesaccery in the first place.

    0 讨论(0)
  • 2020-12-31 11:26

    Sounds like you already know how to do it. If it is a perl script on a unix/linux box then permissions should not be an issue, if it is on a windows box it might not let you as the file is in use

    -- John

    0 讨论(0)
  • 2020-12-31 11:41
    #! /usr/bin/env perl
    use warnings;
    use strict;
    use autodie;
    
    {
      open my $self, '>>', $0;
      my $time = localtime;
      print {$self} "# ran on $time\n";
    }
    
    __END__
    # ran on Wed Aug 25 16:41:05 2010
    
    0 讨论(0)
  • 2020-12-31 11:44

    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.)

    0 讨论(0)
  • 2020-12-31 11:48

    By request adding my comment as an answer.

    Sounds like you already know how to do it. If it is a perl script on a unix/linux box then permissions should not be an issue, if it is on a windows box it might not let you as the file is in use.

    0 讨论(0)
  • 2020-12-31 11:48

    The following worked on a FreeBSD system. It appends to the end, which sounds acceptable to you, but doesn't conform to the "normal" way of documenting changes within a file - at least for me, as I've almost always seen it done at the beginning. You'll probably want to change the way the date/time is displayed.

    #!/usr/bin/perl -w
    open SELF, ">> selfModify.pl" or die "Unable to open self";
    print SELF "# ran/modified at " . join(' ', localtime()) . "\n";
    close(SELF);
    

    Whether this is wise or not I'll leave for you to decide.

    0 讨论(0)
提交回复
热议问题