Perl Style Guide
PVE Perl Style Guide
Various of our files have inconsistent styles due to historical growth as well as because of the mixed styles we got from various contributors.
Please try to follow this guide if you're working on code for PVE to avoid adding to the style mess.
Here's a summary of our style (which is somewhat unusual at least when it comes to the mixed indentation).
Indentation
We indent by 4 spaces, assume tabs to be 8 spaces and convert all groups of 8 spaces into tabs at the beginning of a line. Here's an example, with tabs represented via '>........'
sub foo {
my ($arg1, $arg2, $arg3) = @_;
if ($arg1) {
>.......print($arg2, "\n");
>.......if ($arg3) {
>....... die "Exceptions should end with a newline in most cases\n"
>.......>.......if $arg3 ne $arg2;
>....... print("Another line\n");
>.......}
}
}
Please try to avoid lines longer than 80 characters unless it really ruins the code layout (which often means you want to factorize your code better).
The vim configuration would be `:set ts=8 sts=4 sw=4 noet cc=80`
Like all editors for some reason I'll never understand we do not distinguish between indentation and alignment, so if you split up an expression over multiple lines we still use the same "all 8 spaces are 1 tab" pattern.
Spacing and syntax usage
Spaces around parenthesis with syntactical words are inserted as you would in regular text (one before the opening parenthesis, one after the closing parenthesis). Similarly for curly braces:
- use if (cond) {
- use while (cond) {
- not if(cond) {
- not if (cond){
- not if(cond){
BUT: no space between a function`s name and its parameter list:
- func(params)
- not func (params)
Use spaces around braces of lists:
- use my $list = [ 1, 2, 3 ];
- use my $hash = { one => 1, two => 2 };
No spaces for unary operators or sigils which are directly connected to one another, or in array/hash accesses (here the contents of the brackets or curly braces represent content of the expression/variable to its left, so it makes sense to "group" them):
- use !$foo
- not ! $foo
- use $foo->{text}
- use $foo{text}
- use $foo->[index]
- use $foo[index]
- use &$foo(args)
- not & $foo(args)
In general: use spaces in arithmetic expressions in a way which makes sense, eg. you can skip them on a short single binary operation, or if it helps reading the expression by grouping it so that the operator precedence is emphasized. Do not add spaces in a way which conflicts with the operators' precedences:
- use a + b
- not a+b
- may use a*3 + b*4
- must not use a+3 * b+4
Perl syntax options
Most of these are chosen for semantic clarity and should make it easier to understand the code for people who don't use much perl or simply aren't used to our code base:
- prefer &$foo(args) over $foo->(args)
- prefer $foo->[subscript] over $$[subscript]
- prefer $foo->{subscript} over $${subscript}
- prefer $foo = value if !defined($foo);
- over $foo //= value;