与python同类不同道之perl简记

#与python同类不同道之perl简记

#同类乃同为解释型脚本语言,都支持在黑窗口中直接编程。

#python之道为化一,但perl花样多。

#简单举例如perl中的判断,既有if else,还有unless,其实也很少语言有unless。

#还比如他的循环foreach实现方式也有多种。

#下面是perl的一些语法及用法示例,看完基本能入门

#1.use引入模块

use strict;

use Encode;

use utf8;

#2变量类型:字符串、数字、未定义、列表、哈希

#关键字my定义变量作用域,像局部变量

my $undef = undef;

my $def1 = "this is a string";

my $number1=20180121;

my @array1=("BSDN","百思大脑","yes","nobut","oralenglish");

#3字符串连接

print $undef."contact".$def1;

print "\n", $def1, "\t", $number1;

#4字符串比较,字符串比较应用eq or ne

print "yes" == "no", "\t", "yes" == "yes", "\n";

my $strOne = "this";

print "\n", $strOne eq "this","\t",$strOne eq "that";

#5数组访问及$_作用

print "\n".$array[1];

print "\n1",@array1;

print "\n2";

print foreach @array1;

print $_ foreach @array1;

print "\n3",$_ foreach @array1;

#6循环结构及中断

my @array2=("bstek_product","dorado","urule","ureport","uflo");

foreach $a (@array2){

if($a eq "dorado"){

print "\nbreak";

last;

}

print "\nproduct:",$a;

}

#7哈希结构体定义及析构

my %account=(

"number"=>"20180618",

"opened"=>"2018-01-21",

"owner"=>[{"name"=>"Fry","DOB"=>"2922-2-2"}]

);

print "\n",$account{"number"},"\t",$account{"owner"}->[0]->{"name"};

#8以上用到的$、@、%符号分别定义普通变量,数组,哈希变量必须的首字母标识

#9判断结构:if else unless结构及内置函数length

my $strTwo = "what";

if($strOne eq "when"){

print "\n","true";

}

unless($strOne eq "how"){

print "\n","false";

}

my $word = "If the wrinkles will be engraved on our forhead,what we can only is donot let it engrave in our heart.";

my $strlen = length $word;

if($strlen >= 15) {

print "\n'", $word, "' is a very long word";

} elsif(10

print "\n'", $word, "' is a medium-length word";

} else {

print "\n'", $word, "' is a short word";

}

print "\n'", $word, "' is actually enormous",$strlen if $strlen >= 25;

#10shift作用,每次取数组中一个值,和es6中yield作用一致

print "\n",shift @array;

print "\n",shift @array;

#11自定义函数及@_作用

#函数定义用关键字sub functionName{},不用使用()表示参数;

#函数体内@_代码代表传入函数的参数,可以是哈希结构

sub hyphenate{

my $word = shift @_;

$word = join "-", map(0 .. (length $word)-1);

return $word;

}

print "\n", hyphenate("exterminate");

#12perl其实有2个版本,strawberry perl和activestate perl,相当于社区版和企业版

#13从本行开始,下面用法可能有误待有机会再进一步研究,暂记录在此;类及对象部分内容待补充

#13-1中文字符串比较

my $string1 = "规则";

my $string2 = "规则";

if($string1 eq $string2){

print "\nok";

}

if($string1 ne $string2){

print "\nno";

}

#13-2中文编码问题

my $dat="中文";

print "\n $dat";

my $str=utf8::is_utf8($dat);

print "\n $str";

utf8::downgrade($dat);

print "\n $dat";

my @chars=split//,$str;

print "\n @chars";

#13-3类及对象

  • 发表于:
  • 原文链接http://kuaibao.qq.com/s/20180121G0IXQ300?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码关注云+社区

领取腾讯云代金券