原文见:http://www.programcreek.com/2012/09/10-minutes-perl-tutorial-for-java-developer/
本文并非Java语言和Perl语言的比较文,而是为Java程序员写的快速Perl入门。下面介绍一些要点。 1、基础与Java不同,Perl中没有main方法这样的入口点,要运行下面的Perl程序,比如:
# comment starts with "#" # the name is hello.pl print "Hello Perl!"; 只需执行: perl hello.pl 2、日期类型
Perl语言中的日期类型非常简单,只有3种类型:Scalar、Array和Hash。
Scalar类型即标量,是单个的值,它基本上是除了Array和Hash类型的所有一切。 Array类型是一个数组,可以包含不同类型的元素,比如它可以同时包含整数元素和字符串元素的数组。 Hash类型与Java语言的HashMap类相似。 下面的代码显示了它们的用法:
#claim a hash and assign some values my %aHash; $aHash{'a'}=0; $aHash{'b'}=1; $aHash{'c'}=2; $aHash{'d'}=3; $aHash{'e'}=4; #put all keys to an array my @anArray = keys (%aHash); #loop array and output each scalar foreach my $aScalar (@anArray){ print $aScalar."\n"; } 执行输出: e c a b d 如果想对数组排序,可以简单的使用sort函数,如下: foreach my $aScalar (sort @anArray){ print $aScalar."\n"; } 3、条件语句和循环语句Perl语言的条件语句和循环语句有if、while、for、foreach等关键字,它们和Java语法中的对应关键字很相似。
下面的例子说明了这一点:
#if my $condition = 0; if( $condition == 0){ print "=0\n"; }elsif($condition == 1){ print "=1\n"; }else{ print "others\n"; } #while while($condition < 5){ print $condition; $condition++; } for(my $i=0; $i< 5; $i++){ print $i; } #foreach my @anArray = ("a", 1, 'c'); foreach my $aScalar (sort @anArray){ print $aScalar."\n"; } 4、文件读/写下面的例子说明了如何从文件中读取内容,以及如何向文件写入内容。
要注意“>”和“>>”的不同,前者是创建新文件,后者是向文件添加内容。
#read from a file my $file = "input.txt"; open(my $fh, "<", $file) or die "cannot open < $file!"; while ( my $aline = <$fh> ) { #chomp so no new line character chomp($aline); print $aline; } close $fh; # write to a file my $output = "output.txt"; open (my $fhOutput, ">", $output) or die("Error: Cannot open $output file!"); print $fhOutput "something"; close $fhOutput; |