Perl5 语言废弃了很好的特性,例如 autoref:正则表达式
push $array, name;
Perl5 速度愈来愈快,已经和 Python 不相上下,并且我也最熟悉,加载包也最容易,不过 @INC 加载当前目录,从 5.26 就要取消了。json
把一个 '0xffff' 格式的字符串转换成数字,而后转换成字符:数组
say chr(hex('0x44')); # D say sprintf("0x%x", ord('D')); # 44
翻转一个字符串:函数
scalar reverse('abcde');
原来,单引号字符串中,只有单引号和转义符号自己的转义才有效。编码
my $str = '\\ \'';
前置 if 要对表达式或是值用括号包围起来,原来 Longest Match Rule 能够简化这样的括号。atom
if ($a > $b) { say 'a > b' }
return 的优先级不是最低的,and 比它的还低,因此若是 ruturn 表达式中有 and/or, 要用括号保护起来:.net
sub is_a { my $a = shift; return (length($a) == 1 and $a eq 'a') }
智能匹配符能够匹配数组引用和区间:scala
say 'smart match range ok' if 'a' ~~ ['a'..'z'];
JSON::XS 中的 encode_json 会区别字符串中的 \t \r \f:code
say encode_json(['a', "\t\r\f\n"]); ## => ["a","\t\r\f\n"]
if 表达式中,返回 1 会当成真,返回 0 会当成假。字符串
使用 given .. when 和 smart match : ~~ 要加载声明:
no warnings "experimental"; my $dog = 'Splot'; given ($dog) { when ('Fido') { say 'is Fido' } when ('Splot') { say 'is Splot' } default { say 'not Fido or Splot' } }
smart match 对于字符串来讲,和 eq 同样:
say 'it is same' if 'str' ~~ 'str';
尾部的 if 能够不用括号包围表达式,并且 if 的优先级比 and/or 还要低。
say '$a is a' if length($a) == 1 and $a ~~ 'a';
包名和函数名称不能相同,会发生冲突,由于他们本就在同一个命名空间中:
package PackageName; sub PackageName { say 'hello' }
Perl5 不能直接遍历字符串的字符,要用 split 把字符串拆分红字符数组:
for my $char (split('', $string)) { say $char }
map, List::Util qw(all) 的使用,都不要逗号:
@opt_atoms = map { opt_atom($_) } @atoms; if (all { is_chars($_) } @array) { say 'is chars array' }
substr 的用法:
my $str = '0123456'; say substr($str, -2); # 最后两个字符56 say substr($str, 2); # 从第二个字符后的全部字符, 23456 say substr($str, 2, 2); # 从第二个字符开始,长度为 2 的字符串 23 say substr($str, 2, -2); # 从第二个字符开始,直到倒数第二个字符, 234 say substr($str, -4, -2); # 从倒数第4个字符,到倒数第二个字符, 34
获取字符串中某个字符出现的次数,要用正则表达式:
my @a = ('abcda' =~ /a/g); say scalar(@a);
index 和 rindex 返回的位置是同样的,一个是从前面找,一个从后面,效率不一样罢了。 若是用 index 返回的值作判断,要当心了,没有找到返回的是 -1, 而不是 0, 0 也是找到了
say index('abcde', 'ab'); # 0 say index('abcde', 'de'); # 3 say rindex('abcde', 'de'); # 3 say "$start start with $str" if index( $str, $start ) == 0; say "$str end with $end" if $str ~~ /$end$/;
用正则表达式能够制做不少函数:
# trim $str =~ s/^\s+|\s+$//g;
以 utf8 编码形式读入文件内容:
sub read_file { my $file = shift; error("file: $file not exists") if not -e $file; local $/; open my ($fh), '<:utf8', $file or die $!; return <$fh>; }