$#array代表数组最后一个元素的索引,在需要标量的地方使用@array获取元素的个数。
foreach遍历数组元素
foreach (@array) {
print"This element is $_\n";
}
print$list[$_] foreach0 .. $max;
# you don't have to use the default $_ either...foreachmy$key (keys%hash) {
print"The value of $key is $hash{$key}\n";
}
关于作用域,加my作用域为块,不加my为全局变量
my$x = "foo";
my$some_condition = 1;
if ($some_condition) {
my$y = "bar";
print$x; # prints "foo"print$y; # prints "bar"
}
print$x; # prints "foo"print$y; # prints nothing; $y has fallen out of scope
unless ( condition ) {
...
}
同
if (!condition).
打开一个文件进行输入或者输出
open(my$in, "<", "input.txt") ordie"Can't open input.txt: $!";
open(my$out, ">", "output.txt") ordie"Can't open output.txt: $!";
open(my$log, ">>", "my.log") ordie"Can't open my.log: $!";
用<>来读入一个打开的文件句柄
my$line = <$in>;
my@lines = <$in>;
while (<$in>) { # assigns each line in turn to $_print"Just read in this line: $_";
}
正则表达式
简单匹配
//匹配操作符if (/foo/) { ... } # true if$_ contains "foo"if ($a =~ /foo/) { ... } # true if$a contains "foo"
简单替换
s///替换操作符
s/foo/bar/; # replaces foo with bar in$_$a =~ s/foo/bar/; # replaces foo with bar in$a$a =~ s/foo/bar/g;
# replaces ALL INSTANCES of foo with bar in$a
正则匹配符号
. a single character
\s a whitespace character (space, tab, newline,
...)
\S non-whitespace character
\d a digit (0-9)
\D a non-digit
\w a word character (a-z, A-Z, 0-9, _)
\W a non-word character
[aeiou] matches a single characterin the given set
[^aeiou] matches a single character outside the given
set
(foo|bar|baz) matches any of the alternatives specified
^ start of string
$ end of string
----------
* zero or more of the previous thing
+ one or more of the previous thing
? zero or one of the previous thing
{3} matches exactly 3 of the previous thing
{3,6} matches between 3 and 6 of the previous thing
一些例子:
/^\d+/ string starts with one or more digits
/^$/ nothing in the string (start and end are
adjacent)
/(\d\s){3}/ three digits, each followed by a whitespace
character (eg "3 4 5 ")
/(a.)+/ matches a stringin which every odd-numbered
letter is a (eg "abacadaf")
# This loop reads from STDIN, and prints non-blank lines:
while (<>) {
next if /^$/;
print;
}
将邮件地址拆分为用户名和密码
if ($email =~ /([^@]+)@(.+)/) {
print"Username is $1\n";
print"Hostname is $2\n";
}
子程序
sub logger {my$logmessage = shift;
openmy$logfile, ">>", "my.log"ordie"Could not open my.log: $!";
print$logfile$logmessage;
}
$#array代表数组最后一个元素的索引,在需要标量的地方使用@array获取元素的个数。 foreach遍历数组元素 foreach (@array) { print "This element is $_\n"; } print $list[$_] foreach 0 .. $max; # you don't have to use the default $_ either