为Java程序员准备的10分钟Perl教程

1.从基础开始

不像java,Perl不需要“main”方法作为入口点。要运行一个简单的Perl程序如下:

复制代码 代码如下:
# comment starts with “#”
# the name is hello.pl
print “Hello Perl!”;

只需执行:

perl hello.pl

2. 日期类型

在Perl中的日期类型是非常简单,它有3种类型:标量,数组和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

d

如果你想对数组进行排序,你可以简单地使用类似下面的排序功能:

复制代码 代码如下:
foreach my $aScalar (sort @anArray){
 print $aScalar.”\n”;
}

3. 条件、循环表达式

Perl为条件和循环语句准备了if, while, for, foreach等关键字,这与Java非常类似(switch除外)。

详情请见下面的代码:

复制代码 代码如下:
#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;

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
青葱年少的头像青葱年少普通用户
上一篇 2023年12月28日 下午4:49
下一篇 2023年12月28日 下午4:49

相关推荐