你有好的 Perl 模板脚本吗?

发布于 2024-09-25 00:05:32 字数 105 浏览 3 评论 0 原文

我用 Perl 进行了大量编程,想知道人们是否有一个他们使用并愿意共享的“默认”模板 Perl 脚本。

我开始复制一个具有 Getopt 函数的旧脚本。我想人们也会做类似的事情吗?

I do a lot of programming in Perl and was wondering if people had a "default" template Perl script that they use and willing to share.

I started copying one of my older scripts which has Getopt functions. I am thinking people would have done something similar?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

陌路终见情 2024-10-02 00:05:32

在我的 .vimrc 文件中,我可以

au BufNewFile *.pl s-^-#!/usr/bin/perl\r\ruse strict;\ruse warnings;\r\r-

写入

#!/usr/bin/perl

use strict;
use warnings;

任何新的 Perl 脚本。我也有

au BufNewFile *.pm s-^-package XXX;\r\ruse strict;\ruse warnings;\r\r1;-

模块,但我倾向于使用 Module无论如何,::Starter

In my .vimrc file I have

au BufNewFile *.pl s-^-#!/usr/bin/perl\r\ruse strict;\ruse warnings;\r\r-

which writes

#!/usr/bin/perl

use strict;
use warnings;

to any new Perl script. I also have

au BufNewFile *.pm s-^-package XXX;\r\ruse strict;\ruse warnings;\r\r1;-

for modules, but I tend to use Module::Starter for those anyway.

远昼 2024-10-02 00:05:32

当我需要许多类似脚本的基本模板时,我只需将类似的部分变成一个模块即可。然后,脚本简化为如下内容:

 use App::Foo;

 App::Foo->run( @ARGV );

App::Foo 将从模板模块继承并覆盖任何不同的内容:

 package App::Foo;
 use parent qw(App::Template);

 ...

App::Template 模块中,您输入无论你需要什么:

 package App::Template;

 sub run {
    my( $class, @args ) = @_;

    my $self = $class->new( ... );
    $self->init;
    $self->process_command_line( ... );

    ...
    }


 sub process_command_line { ... }

 ...

CPAN 上有一些针对此类事情的框架,但我认为自己做同样容易,并且无需处理不需要的部分即可获得所需的内容。

When I need a basic template for many similar scripts, I just turn the similar parts into a module. The script then reduces to something like:

 use App::Foo;

 App::Foo->run( @ARGV );

The App::Foo would inherit from the template module and override whatever was different:

 package App::Foo;
 use parent qw(App::Template);

 ...

In the App::Template module, you put in whatever you need:

 package App::Template;

 sub run {
    my( $class, @args ) = @_;

    my $self = $class->new( ... );
    $self->init;
    $self->process_command_line( ... );

    ...
    }


 sub process_command_line { ... }

 ...

There are some frameworks on CPAN for this sort of thing, but I think it's just as easy to do it yourself and get exactly what you need without dealing with the parts you don't need.

浅忆 2024-10-02 00:05:32

正如人们在我将方法模板放入模块之前所说的那样:use PMG::PMGBase; 对于初始脚本转义,作为 emacs 用户,我有我的 perl-insert-start 和 perl-add -getoption 模板,但是写这样的东西:

(defun perl-insert-start ()
  "Places #!..perl at the start of the script"
  (interactive)
  (goto-char (point-min))
  (insert "#!/usr/bin/env perl\n\n")
  (insert "=head1 [progam_name]\n\n")
  (insert " description:\n\n")
  (insert "=cut\n\n")
  (insert "use feature ':5.10';\n")
  (insert "use strict;\n")
  (insert "#use warnings;\n")
  (insert "#use Data::Dumper;\n")
)

有点烦人。所以最后对我来说更容易拥有一个 Perl 模板脚本(见下文),并使用 run-command-on-region 调用它: Cu M-|在空白缓冲区中选择一个空格后,从 Emacs 中输入:~/scripts/perl-start-template.pl:

#!/usr/bin/env perl

=head1 [progam_name]

 description:

=cut

use feature ':5.10';
use strict;
use Getopt::Long;

my $prog = $0;
my $usage = <<EOQ;
Usage for $0:

  >$prog [-test -help -verbose]

EOQ

my $help;
my $test;
my $debug;
my $verbose =1;


my $ok = GetOptions(
                    'test'      => \$test,
                    'debug:i'   => \$debug,
                    'verbose:i' => \$verbose,
                    'help'      => \$help,
                   );

if ($help || !$ok ) {
    print $usage;
    exit;
}


print template();


sub template {
    ##
    ### Here start the template code
    ##
    return <<'EOT';
#!/usr/bin/env perl

=head1 [progam_name]

 description: This script prints a template for new perl scripts

=cut

use feature ':5.10';
use strict;
#use warnings;
#use Data::Dumper;
use Getopt::Long;
# use Template;
# use PMG::PMGBase;  
# use File::Temp qw/ tempfile tempdir /;
# use File::Slurp;
# use File::Copy;
# use File::Path;
# use File::Spec;
# use File::Basename qw(basename dirname);
# use List::Util qw(reduce max min);
# use List::MoreUtils qw(uniq indexes each_arrayref natatime);

# my $PMGbase = PMG::PMGBase->new();
my $prog = $0;
my $usage = <<EOQ;
Usage for $0:

  >$prog [-test -help -verbose]

EOQ

my $date = get_date();

my $help;
my $test;
my $debug;
my $verbose =1;

my $bsub;
my $log;
my $stdout;
my $stdin;
my $run;
my $dry_run;

my $ok = GetOptions(
                    'test'      => \$test,
                    'debug:i'   => \$debug,
                    'verbose:i' => \$verbose,
                    'help'      => \$help,
                    'log'       => \$log,
                    'bsub'      => \$bsub,
                    'stdout'    => \$stdout,
                    'stdin'     => \$stdin,

                    'run'       => \$run,
                    'dry_run'   => \$dry_run,

                   );

if ($help || !$ok ) {
    print $usage;
    exit;
}

sub get_date {

    my ($day, $mon, $year) = (localtime)[3..5] ;

    return my $date= sprintf "%04d-%02d-%02d", $year+1900, $mon+1, $day;
}

sub parse_csv_args {

    my $csv_str =shift;
    return [split ',', $csv_str];
}

EOT


}

As people say before I have my methods templates in a module: use PMG::PMGBase; and for the initial script escafolding, as an emacs user, I have my perl-insert-start and perl-add-getoption templates, but writing things like:

(defun perl-insert-start ()
  "Places #!..perl at the start of the script"
  (interactive)
  (goto-char (point-min))
  (insert "#!/usr/bin/env perl\n\n")
  (insert "=head1 [progam_name]\n\n")
  (insert " description:\n\n")
  (insert "=cut\n\n")
  (insert "use feature ':5.10';\n")
  (insert "use strict;\n")
  (insert "#use warnings;\n")
  (insert "#use Data::Dumper;\n")
)

is a bit tiresome. So at the end is easier for me to have a Perl template script (see below), and call it with run-command-on-region: C-u M-| :~/scripts/perl-start-template.pl from Emacs after selecting one space in a blank buffer:

#!/usr/bin/env perl

=head1 [progam_name]

 description:

=cut

use feature ':5.10';
use strict;
use Getopt::Long;

my $prog = $0;
my $usage = <<EOQ;
Usage for $0:

  >$prog [-test -help -verbose]

EOQ

my $help;
my $test;
my $debug;
my $verbose =1;


my $ok = GetOptions(
                    'test'      => \$test,
                    'debug:i'   => \$debug,
                    'verbose:i' => \$verbose,
                    'help'      => \$help,
                   );

if ($help || !$ok ) {
    print $usage;
    exit;
}


print template();


sub template {
    ##
    ### Here start the template code
    ##
    return <<'EOT';
#!/usr/bin/env perl

=head1 [progam_name]

 description: This script prints a template for new perl scripts

=cut

use feature ':5.10';
use strict;
#use warnings;
#use Data::Dumper;
use Getopt::Long;
# use Template;
# use PMG::PMGBase;  
# use File::Temp qw/ tempfile tempdir /;
# use File::Slurp;
# use File::Copy;
# use File::Path;
# use File::Spec;
# use File::Basename qw(basename dirname);
# use List::Util qw(reduce max min);
# use List::MoreUtils qw(uniq indexes each_arrayref natatime);

# my $PMGbase = PMG::PMGBase->new();
my $prog = $0;
my $usage = <<EOQ;
Usage for $0:

  >$prog [-test -help -verbose]

EOQ

my $date = get_date();

my $help;
my $test;
my $debug;
my $verbose =1;

my $bsub;
my $log;
my $stdout;
my $stdin;
my $run;
my $dry_run;

my $ok = GetOptions(
                    'test'      => \$test,
                    'debug:i'   => \$debug,
                    'verbose:i' => \$verbose,
                    'help'      => \$help,
                    'log'       => \$log,
                    'bsub'      => \$bsub,
                    'stdout'    => \$stdout,
                    'stdin'     => \$stdin,

                    'run'       => \$run,
                    'dry_run'   => \$dry_run,

                   );

if ($help || !$ok ) {
    print $usage;
    exit;
}

sub get_date {

    my ($day, $mon, $year) = (localtime)[3..5] ;

    return my $date= sprintf "%04d-%02d-%02d", $year+1900, $mon+1, $day;
}

sub parse_csv_args {

    my $csv_str =shift;
    return [split ',', $csv_str];
}

EOT


}
棒棒糖 2024-10-02 00:05:32

我的很简单。

#!/usr/bin/perl
use Modern::Perl

当涉及到像 getopt 这样的事情时,我编写的脚本之间没有足够的共同点,因此值得拥有更详细的模板。

Mine is pretty simple.

#!/usr/bin/perl
use Modern::Perl

When it comes to things like getopt, there aren't enough commonalities among the scripts I write to make it worth while having a more verbose template.

笑,眼淚并存 2024-10-02 00:05:32

我有两个。一个旧的只不过是 perl 单行的包装器,而第二个则具有更多我经常发现有用的功能和示例:

#!/usr/bin/perl
# name_of_script ver 0.01 YYYYMMDD [email protected]
use strict;
no strict "refs";


sub footer
{
    my $this_year=`date +%Y`; chop($this_year);
    print "Copyright 2003-$this_year You or Company\n";
    # This isn't how copyright works -  the dates cove the time when the code
    #  was created.
}

sub help
{
    print "Usage: $0\n";
    &footer;
exit(0);
}

if( ($ARGV[0] =~ /^-+h/i) || (!$ARGV[0]) )
{
    &help;
}
##### code


##### end of code
print "Done that\n";

exit(0);

我使用上面的进行快速测试,但更经常使用以下,(当我'我不会破解整个模块。)

#!/usr/bin/perl
# name_of_script ver 0.01 YYYYMMDD [email protected]
use strict;
{
no strict "refs"; # this helps bypass frustration when I'm doing it wrong.
}

=head1 NAME

name_of_script

=head1 VERSION

0.01

=cut

our $VERSION = 0.01;

=head1 ABSTRACT

A synopsis of the new script

=head1 DESCRIPTION

Provide an overview of functionality and purpose of
this script

=head1 OPTIONS

%opt stores the global variables
%ignore overrides %opt

=cut

my (%opt,%ignore);

=head2 ARGS

=over 8

=item B<-h> send for help (just spits out this POD by default, but we can chose something else if we like 

=back

=head3 other arguments and flags that are valid

For when GetOpt is too heavy

-d -v -i[!] (value) 

=cut

for(my $args=0;$args<=(@ARGV -1);$args++){
    if ($ARGV[$args]=~m/^-+h/i){ &help; }
    elsif ($ARGV[$args] eq '-d'){ $opt{D}++; }
    elsif ($ARGV[$args] eq '-v'){ $opt{verbose}++;  print "Verbose output not implemented yet - try debug\n";}
    elsif ($ARGV[$args]=~m/-+i!(.+)/){ delete($ignore{$1}); }
    elsif ($ARGV[$args]=~m/-+record(.+)/){ $opt{record_data}++; }
    elsif ($ARGV[$args]=~m/-+w(ipe_home_dirs)?/){ $opt{wipe_home_dirs}++; }
    elsif ($ARGV[$args]=~m/-+i(.+)/){ $ignore{$1}=1; }
    elsif ($ARGV[$args]=~m/-+path(.+)/){ $opt{BASE_PATH} = $1; }
    elsif ($ARGV[$args]=~m/-+path/){ $args++; $opt{BASE_PATH} = $ARGV[$args]; }
    elsif ($ARGV[$args]=~m/-+dir(.+)/){ $opt{BASE_PATH} = $1; }
    elsif ($ARGV[$args] eq '-no-xml'||$ARGV[$args] eq '-no_xml'){ delete $opt{xml}; }
    elsif ($ARGV[$args] eq '-no-mkdir'||$ARGV[$args] eq '-no_mkdir'){ delete $opt{mkdir}; }
    elsif ($ARGV[$args] !~m/^-/ && -d "$ARGV[$args]"){ push @{ $opt{paths} }, $ARGV[$args] }
    else{ print "what is this $ARGV[$args] you talk of?\n"; &help; }
}


=head1 METHODS

=head3 footer

Adds the Copyright line to any output that needs it

=cut

sub footer { print "perldoc $0 \nCopyright 2011 You or Company\n"; }

=head3 help

Just the help output

=cut

sub help {
    print `perldoc $0`;
    #print "Usage: $0\n";
    #&footer;
    exit(0);
}

##### code


##### end of code

=head1 BUGS AND LIMITATIONS

There are no known problems with this script.
Please report any bugs or feature requests

=head1 SEE ALSO

#L<My::Modules>

=head1 MAINTAINER

is the AUTHOR

=head1 AUTHOR

Some Person, C<<some.person at example.com>>

=head1 LICENSE AND COPYRIGHT

Copyright 2011 Alexx Roche, all rights reserved.

This program is free software; you can redistribute it and/or modify it
under the terms of either: Eclipse Public License, Version 1.0 ; 
 the GNU Lesser General Public License as published 
by the Free Software Foundation; or the Artistic License.

See http://www.opensource.org/licenses/ for more information.

=cut

print "Done that\n" if $opt{verbose}>=1;
exit(0);
__END__

__END__ 通常仅在我们要在代码后添加 POD 时使用
如果您将“完成”移到 POD 上方,那么 __END__ 对我来说更有意义。

您可以随意破解这两个。我在这里并没有声称自己有良好的风格或实践,(有时我会从较短的代码开始,然后粘贴较长的代码块,因为我需要它们最终得到两种代码风格的巨魔。)

I have two. An old one which is little more than a wrapper to a perl one-liner and a second that has more functions and examples that I often find useful:

#!/usr/bin/perl
# name_of_script ver 0.01 YYYYMMDD [email protected]
use strict;
no strict "refs";


sub footer
{
    my $this_year=`date +%Y`; chop($this_year);
    print "Copyright 2003-$this_year You or Company\n";
    # This isn't how copyright works -  the dates cove the time when the code
    #  was created.
}

sub help
{
    print "Usage: $0\n";
    &footer;
exit(0);
}

if( ($ARGV[0] =~ /^-+h/i) || (!$ARGV[0]) )
{
    &help;
}
##### code


##### end of code
print "Done that\n";

exit(0);

I use the above for quick test but more often I use the following, (when I'm not hacking a full module.)

#!/usr/bin/perl
# name_of_script ver 0.01 YYYYMMDD [email protected]
use strict;
{
no strict "refs"; # this helps bypass frustration when I'm doing it wrong.
}

=head1 NAME

name_of_script

=head1 VERSION

0.01

=cut

our $VERSION = 0.01;

=head1 ABSTRACT

A synopsis of the new script

=head1 DESCRIPTION

Provide an overview of functionality and purpose of
this script

=head1 OPTIONS

%opt stores the global variables
%ignore overrides %opt

=cut

my (%opt,%ignore);

=head2 ARGS

=over 8

=item B<-h> send for help (just spits out this POD by default, but we can chose something else if we like 

=back

=head3 other arguments and flags that are valid

For when GetOpt is too heavy

-d -v -i[!] (value) 

=cut

for(my $args=0;$args<=(@ARGV -1);$args++){
    if ($ARGV[$args]=~m/^-+h/i){ &help; }
    elsif ($ARGV[$args] eq '-d'){ $opt{D}++; }
    elsif ($ARGV[$args] eq '-v'){ $opt{verbose}++;  print "Verbose output not implemented yet - try debug\n";}
    elsif ($ARGV[$args]=~m/-+i!(.+)/){ delete($ignore{$1}); }
    elsif ($ARGV[$args]=~m/-+record(.+)/){ $opt{record_data}++; }
    elsif ($ARGV[$args]=~m/-+w(ipe_home_dirs)?/){ $opt{wipe_home_dirs}++; }
    elsif ($ARGV[$args]=~m/-+i(.+)/){ $ignore{$1}=1; }
    elsif ($ARGV[$args]=~m/-+path(.+)/){ $opt{BASE_PATH} = $1; }
    elsif ($ARGV[$args]=~m/-+path/){ $args++; $opt{BASE_PATH} = $ARGV[$args]; }
    elsif ($ARGV[$args]=~m/-+dir(.+)/){ $opt{BASE_PATH} = $1; }
    elsif ($ARGV[$args] eq '-no-xml'||$ARGV[$args] eq '-no_xml'){ delete $opt{xml}; }
    elsif ($ARGV[$args] eq '-no-mkdir'||$ARGV[$args] eq '-no_mkdir'){ delete $opt{mkdir}; }
    elsif ($ARGV[$args] !~m/^-/ && -d "$ARGV[$args]"){ push @{ $opt{paths} }, $ARGV[$args] }
    else{ print "what is this $ARGV[$args] you talk of?\n"; &help; }
}


=head1 METHODS

=head3 footer

Adds the Copyright line to any output that needs it

=cut

sub footer { print "perldoc $0 \nCopyright 2011 You or Company\n"; }

=head3 help

Just the help output

=cut

sub help {
    print `perldoc $0`;
    #print "Usage: $0\n";
    #&footer;
    exit(0);
}

##### code


##### end of code

=head1 BUGS AND LIMITATIONS

There are no known problems with this script.
Please report any bugs or feature requests

=head1 SEE ALSO

#L<My::Modules>

=head1 MAINTAINER

is the AUTHOR

=head1 AUTHOR

Some Person, C<<some.person at example.com>>

=head1 LICENSE AND COPYRIGHT

Copyright 2011 Alexx Roche, all rights reserved.

This program is free software; you can redistribute it and/or modify it
under the terms of either: Eclipse Public License, Version 1.0 ; 
 the GNU Lesser General Public License as published 
by the Free Software Foundation; or the Artistic License.

See http://www.opensource.org/licenses/ for more information.

=cut

print "Done that\n" if $opt{verbose}>=1;
exit(0);
__END__

__END__ is usually only used if we are going to have POD after the code
If you move the "Done that" above the POD then __END__ makes more sense to me.

Feel free to hack these two about as much as you like. I make no claims to good style or practices here, (and I sometimes start with the short one and paste in blocks from the longer one as I need them ending up with two code styles for the trolols.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文