codecamp

风格

camelCase 很糟

你曾维护过别人的代码吗?你维护过像这样的代码吗?

my $variableThatContainsData =
    someSubroutineThatMucksWithData( $someAwfulVariable );

混合大小写单词在 Perl 世界被称为 camelCase,通常它的令人不悦之处是使 阅读代码更难。

甚至具有糟糕名称的代码使用下划线也能变得更可读:

my $variable_that_contains_data = 
    some_subroutine_that_mucks_with_data( $some_awful_variable );

warnings 和 strict

对于你希望维护、重用、及发布的任何程序,都应当具有下列代码行:

#!/usr/bin/perl

use strict;
use warnings;

启用 strict 使 Perl 抱怨不确定的代码结构,比如:未声明的变量、祼字、 以及软引用等。这些警告将导致 Perl 执行失败。

#!/usr/bin/perl
use strict;

$foo    = 4;     # undeclared variable error
$foo    = Bar;   # bareword error
my $bat = "foo";
print $$bat;     # reference error

启用 warnings 使 Perl 甚至抱怨更多东东。但不像 strict,这些抱怨在 一般条件下并不严重。

#!/usr/bin/perl
use warnings;
$a + 0;                      # void context warning
                             # name used once warning
                             # undef warning
print "program continued\n"; # prints

如果你想要 warnings 变得严重,告诉它:

use warnings FATAL => 'all';
$a + 0;                      # void warning and then exits
print "program continued\n"; # doesn't print

使用 perltidy 格式化 Perl 源代码

选择何种代码风格是仁者见仁,智者见智的事情。但重要的是保持风格的一致性。 为了使格式化 Perl 源代码更容易,你可以使用 Perl::Tidy 模块随付的 perltidy 工具。

例如,使用 Perl 最佳实践 一书所推荐的风格来格式化源代码:

$ perltidy -pbp myprogram.pl -o myprogram.formated.pl
高级函数
性能
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }