Skip to content

Perl Basics

Ben Chen edited this page Jul 24, 2017 · 2 revisions

Table of Contents

Perl Basics

References

语法注意事项

  • 单引号无法解析转义符和变量,会按原样输出,如:
$a = 10;
print "a = $a\n"; # a = 10
print 'a = $a\n'; # a = $a\n
  • heredoc

数据类型

Scalar

标量,可表示字符、字符串、整数、浮点数。

my $x = "abc";
my $x = 123;
my $x = 4.56;

Array

标量数组。

my @array;
my @array = qw(a b c d);
# 等价于:
my @array = ("a", "b", "c", "d");
$array[0] = "a";

# for loop:
for($i = 0; $i <= $#array; $i++) {
    print "$array[$i]\n";
}
$#array 表示最后一个元素的下标

# 排序:
foreach my $aScalar (@array){
	print $aScalar."\n";
}

Hash

哈希表。

my %hash = ("i1"=>"aaa", "i2"=>"bbb");
# 等价于
my %hash = ("i1", "aaa", "i2", "bbb");

# 存取元素
$hash{'i1'} = "aaa";

# 其他使用
foreach $key (keys %hash) {
    print "$hash{$key}\n";
}
foreach $value (values $hash)
while(($key, $value) = each %hash)

控制语句

if(...) { ... } elsif(...) { ... } else { ... }

while(chomp($i=<STDIN>)) {
    next if ($i == 5); # 类似 continue
    last unless ($i > 10); # 类似 break
}

for(my $i = 0; $i < 10; $i++) { ... }
for $i (0..9) {Code Segment}

foreach my @aScalar (sort @anArray) { ... }

文件读写

#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;

正则表达式

主要有两个用到正则表达式的函数:ms

# 对$str匹配正则表达式,返回true或false
$str =~ m/program(creek|river)/

按值/引用传递

数组:

my @testArray = (1, 3, 2);
 
#In sub
sub processArrayByReference($) {
	my $arrayref = shift;
	my @array    = @$arrayref;
	#...
}
 
#In sub processarray:
sub processArrayByValue($){
	my @array = @_;
	#...
}
 
processArrayByValue(@testArray);
 
processArrayByReference( \@testArray );

哈希表:

sub printHash($) {
	my %hash = %{ shift() };
	for my $key ( sort keys %hash ) {
		my $value = $hash{$key};
		print "$key => $value\n";
	}
}
 
printHash(\%twoLettersCount);

一些酷/复杂例子

  1. 遍历字符串的字符
my @lineCharArray = split('',$aline);
 
foreach my $character (@lineCharArray){
	print $character."\n";
}
  1. 创建包含26个字母的数组
my @charArray = ('a'..'z' );
my @twoCharArray = ('aa'..'zz');

Clone this wiki locally