2014-09-24 31 views
3

我得到了一個perl腳本,它有主腳本和一對子程序交織在一起。它看起來像:Perl如何在子程序和主腳本之間組織代碼

sub utils1 { 
    ... 
} 

# some code 
# some more code that calls utils1 

sub utils2 { 
    ... 
} 

# some code that calls utils2 

sub utils3 { 
    ... 
} 

# some code that calls utils3 
# the rest of code 

是否有更好的方法來組織代碼?尋找一個好的編碼習慣。基於我的python編碼經驗,我在想下面的東西。這看起來如何?

sub utils1 { 
    ... 
} 

sub utils2 { 
    ... 
} 

sub utils3 { 
    ... 
} 

sub main { 
    # some code 
    # some more code that calls utils1 
    # some code that calls utils2 
    # some code that calls utils3 
    # the rest of code 
} 

&main(); 
+3

您正在使用哪個版本的Perl?爲什麼你用'&'和'main()'?這可能對你有用:http://eev.ee/blog/2011/04/13/perl-worst-practices/ – Biffen 2014-09-24 10:00:45

+1

小問題:perl子程序是用'sub'而不是'subroutine'聲明的... – 2014-09-24 10:00:54

+3

[現代Perl](http://modernperlbooks.com/books/modern_perl_2014/index.html)有一個很棒的(免費!)現代perl實踐指南。 – 2014-09-24 10:05:06

回答

2

據我所知是沒有的子程序的組織定義best-practice。根據我的經驗,文檔通常會指示訂單。

E.g.

use Getopt::Lucid; 

=head1 SYNOPSIS 

This program does nothing so long ... 

=cut 

# ... main code here, not necessary to wrap into a sub 

=head1 PUBLIC METHODS 

=cut 

sub method1 { 

=head2 method1 

This method does something ... 

=cut 

    $self = shift; 
    # ... 
} 

sub method2 { 

=head2 method2 

This method does something different... 

=cut 

    $self = shift; 
    # ... 
} 

=head1 PRIVATE METHODS 

These methods are private their interface may change. 

=cut 

sub _priv1 { 

=head2 _priv1 

The _priv1 method is for ... and used by .... 

=cut 

    my $self = shift; 
    # ... 
}