+IdentityFile ~/.ssh/id_dsa-sourceware
[nethome.git] / src / Perl-Style
1 $Id$
2
3 Important lines prefixed by '[!](?:(?!\s)| )'.
4 General (non-Perl) lines prefixed by '[~](?:(?!\s)| )'.
5 Perl general knowledge from docs prefixed by '[#](?:(?!\s)| )'.
6
7 Perl-5.0+ header:
8 !               #! /usr/bin/perl -w
9                 #
10                 #       $Id$
11
12                 package My::Package::Name;
13 !               use vars qw($VERSION);
14 ! #             $VERSION=do { my @r=(q$Revision$=~/\d+/g); sprintf "%d.".("%03d"x$#r),@r; };
15 !               use strict;
16                 #use warnings;
17         * Note 'sprintf' hack to keep Perl MakeMaker numbering linear with CVS.
18         * Always using 'strict'/'warnings'
19         * Not sure if one has right to declare own non-CPAN-accepted package
20           name outside of 'My::' prefix, recently using always rather 'My::'
21
22 Perl-5.6.0+ header:
23 !       #! /usr/bin/perl
24         #
25         #       $Id$
26
27         package My::Package::Name;
28 ! #     our $VERSION=do { my @r=(q$Revision$=~/\d+/g); sprintf "%d.".("%03d"x$#r),@r; };
29 !       use strict;
30 !       use warnings;
31
32
33 Header block for OO files and/or exporting files:
34         require My::Inherited1;
35         require My::Inherited2;
36         require Exporter;
37         use vars qw(@ISA @EXPORT);
38         @ISA=qw(My::Inherited1 My::Inherited2 Exporter);
39         @EXPORT=qw();
40
41 Generally always rather 'require' than 'use'. Modules with non-conflicting
42 naming are 'use'd (such as 'MIME::Base64' with &encode_base64 etc.).
43
44 Method parenthesis:
45 !       * Always given if no arguments are passed.
46 !       * Always given for any object or class method calls.
47 !       * Always given if the first arguments looks as bless()ed.
48         * docs/comments: 'method()' used for invocation, '&method' for reference
49 !       * Always given for 'map', 'each' (commands-not methods from previous line)
50         * Trying to prevent if not neccessary
51 !       * Usually needed for 'print' argument as its first arg already has '()'
52 !       * Never using 'method_name blessed_object' syntax:
53                 Dangerous:
54                         name blessed_object
55                 interpreted as
56                         blessed_object->name()
57                 instead of intended
58                         name(blessed_object)
59
60 Always use named control variable for 'for my $var (...)' if the naming makes
61 sense, leave the default '$_' instead of common names such as $i or $n.
62
63 Function header:
64                 # $first_arg,%$secondarg,@rest
65                 sub function_name
66                 {
67                 my($class,first_arg,$secondarg,@rest)=@_;
68         * Comment-line suppressed if trivial.
69         * Comment-line written in the dereferencing operators order being used
70           for accessing elements.
71 !       * Suicide imminent if '=@_' forgotten.
72         * Always used $class or $self for class-methods or object-methods.
73                 * Usually not using (caller should call it manually):
74                         $self=$self->new() if !ref $self;
75 !       * Never modifying @_ to keep perl debugger 'T' command happy
76         * Wanna use function prototypes (not yet) although I will never use
77           '\', '*' or '&' for the same reasons I would never use C++ '&' param.
78
79 Not using: 'unless'(->'if !'), 'until'(->'while !'), 'foreach'(->'for').
80
81 Always trying to use 'map' instead of 'for'. Nested 'map's are fined although
82 $_ renaming is needed there:
83         map({
84 !               my $whole_record=$_;
85                 map({ $_+$whole_record->{"shift_value"}; } ($whole_record->{"list"}));
86                 } @some_record_list)
87
88 Always trying to place 'for'/'if'/'while' after the command (without block).
89         * Impossible if multiple modifiers needed (just one placed after):
90 !               print "$_\n" for (0..5) if $do_print;
91         * Impossible if using variable declared in the modifier:
92 !               print "$var\n" for my $var (@some_array);
93         * Sometimes even using for multiple commands under the control:
94                         do { print "kaboom"; return; } if $serious_problem;
95                 do not use this as even 'print' can fail:
96                         print "kaboom" and return if $serious_problem;
97                 (and it uses unclear precedence rules)
98
99 OO constructor always named &new or &new_*.
100
101 Utility functions without any OO sense do not use $class or $self.
102
103 Rather referrencing rvalue than dereferrencing lvalue:
104                 @{$ref->{"array"}}=(1,2,3);
105         never used, I like rather:
106                 $ref->{"array"}=[1,2,3];
107
108 Lists parenthesed where passed as 'list' argument:
109                 map({ some_function_body; } listarg1,listarg2);
110         never used, I like rather:
111                 map({ some_function_body; } (listarg1,listarg2));
112         * parentheses suppressed if simple '@array_name' is passed.
113
114 Last command of block { } always suffixed by its ';'.
115
116 String substitution used only for simple scalars, concatenation used otherwise:
117                 print "total_crashes: $left or $maybe->{'crashes'}\n";
118         never used, I like rather:
119                 print "total_crashes: $crashes or ".$maybe->{'crashes'}."\n";
120
121 Conditional expressions 'a?b:c' usually use the same item
122         $record->{"field"}==5 ? 7 : $record->{"field"}+1
123 can be nicely rewritten as:
124 !       map(($_==5 ? 7 : $_+1),$record->{"field"})
125
126 while(<HANDLE>) modifies $_ without its localization! Needed everywhere:
127 ! #     local $_;
128         while (<HANDLE>) {
129                 some_commands;
130                 }
131
132 Never used barewords for hash keys, always quoted:
133                 $hashref->{somekey}
134         never used, I like rather:
135 !               $hashref->{"somekey"}
136 as it can crash for some reseverd words used as 'somekey'.
137
138 You cannot use positive-case substitution in list context:
139                 @list=($user_wishes{"provide_arg"} && "real_arg");
140         does '@list=(undef()); @list==1; #YES' if !$user_wishes{"provide_arg"},
141         instead you must code the full ugly construction:
142 !               @list=(!$user_wishes{"provide_arg"} ? () : ("real_arg"));
143
144 ~ Conditional-evaluation always shortcut optimized by providing the trivial case
145 as the first one of two branches (even if such trivial branch has more source
146 code letters to write).
147                 @new_list=(!@list ? (list_is_empty(\@list)) : @list);
148         although sometimes the meaning of 'trivial case' can be subjective.
149
150 # Private methods named as &_method (still must be called as _method()!).
151
152 ~ Value being prepared for return named 'r'.
153
154 It may get handy to use:
155         confess if !wantarray() && 2<=@r;       # optional and sometimes not appropriate
156         return wantarray() ? @r : $r[0];
157
158 Never using 'die' or 'warn', always 'confess' or 'cluck'
159 (and never 'carp' or 'cloak'):
160         use Carp qw(cluck confess);
161
162 Always local()ize file handle globref if not in package 'main':
163 !       local *F;
164         do { open F,$_ or confess "$_: $!"; } for ("some_file");
165
166 There are many ways to code 'C switch(){}', I use:
167                    if (cond1) {
168                         }
169                 elsif (cond2) {
170                         }
171                 else {
172                         }
173         although it is deprecated by Perl doc but they do not give much better
174         solutions. Some of them are restricted to single command body ('do {}'
175         needed) etc. if-elsif-else method would be shorter in the code if
176                 } elsif (condX) {
177         indenting style is used.
178
179 ~ Function definitions ordered lower->higher to prevent pre-declarations.
180
181 ! For any non-trivial data structures it is essential to differentiate between:
182         scalar, list, array, hash, ref to scalar, ref to array, ref to hash
183
184 Any missing trailing function parameters appear as undef().
185 Any passed trailing undef()s can still be properly detected and interpreted:
186         scalar(@_) will still report the real number of parameters.
187         undef() is the real parameter.
188
189 Perl is too damn slow during startup but it is blazingly fast when it runs.
190 mod_perl prevents this startup overhead (present in standalone Perl CGIs).
191 'Storable'-disk-dumped complex memory data structures are 10x larger in memory
192 as reported by http://petamem.com .
193
194 Curly-bracketing all subexpressions for dereferencign explicitely if not trivial:
195                 my %rec=("x"=>["a\n","b\n"]);print @$rec{"x"};
196                 print @$arrayref;
197         would not work as it would mean:
198                 my %rec=("x"=>["a\n","b\n"]);print @{$rec}{"x"};
199                 print @$arrayref;
200         , I like rather even if it would work without curly-bracketing:
201 !               my %rec=("x"=>["a\n","b\n"]);print @{$rec{"x"}};
202                 print @$arrayref;
203
204 Declaration scope of 'my' in the non-sub{} file: Whole file inside one package.
205 Declaration scope of 'my' in sub{} or block {}: Only in { }, not accessible by callees.
206 Declaration scope of 'local': This sub{} and globally for all callees.
207         * Perfect for some nesting counters:
208                 my $func_nest=0;
209                 sub func
210                 {
211                 # automatically restored after exit from &func
212                 local $func_nest=$func_nest+1;
213                 }
214         * Built-in variables cannot be 'my' scoped, use 'local' instead
215 Declaration scope of 'our'(5.6.0+) or 'use vars...': Global across packages.
216 (These scoping rules are simplified but works4me.)