本文共 1805 字,大约阅读时间需要 6 分钟。
在 Perl 中,括号用于赋值和初始化数组或哈希。小括号 () 用于赋值,中括号 [] 用于数组引用,大括号 {} 用于哈希引用。
数组赋值
$hash = %hash=("foo", 35, "bar", "12.4");这个语句初始化了一个哈希,键值对分别是 foo 和 bar 对应的值 35 和 "12.4"。
列表赋值
($fred, $barney) = qw(a b c d);
这个语句将数组 a b c d 分配给变量 $fred 和 $barney。
空数组或空哈希
@line = (); # 空数组$hash = %hash = (); # 空哈希
中括号 用于数组下标和匿名数组的引用:
$array_r = [1, 2, 3, 4, 5];
大括号 用于匿名哈希的引用:
$hash_r = { apple => "pomme", pear => "poire" };访问哈希元素:
$hash_r{"fr"} = "flint";数组引用
$array = (1, 2, 3, 4, 5);$array_r = $array;$array2 = @{$array_r}; # 拷贝数组在 Perl 中,列表 和 数组 是等价的概念,主要区别在于赋值方式:
$a = <==> # 读取一行,标量@a = <==> # 读取多行,数组
使用 perl -n 模式读取文件:
perl -n 'print scalar <==>;'
加上 -n 会自动处理每一行。
while (<==>) { push(@a, $_);} 循环读取并存储每一行。
perl -pe '@A=<==>; print @A[-10..-1]'
使用负值范围可以从末尾开始提取元素。
长度处理:
$str = "1234567";@a = split(//, $str);
没有分隔符时会默认分割空白。
字符串长度:
$d1 = length(@d);$d2 = 1;
字符串转数组:
$f = "@d"; # 转换为字符串$g = join("\n", @d); # 转换为多行字符串perl -e 'print reverse <==>;'
perl -ple '$_ = reverse'
perl -pe '$_ .= "\n\n"'
perl -pe 'print " "x5'
< 到 >:$string =~ s/<.*?>/g;
scarlet、ruby 为 red:perl -pe 's/scarlet|ruby|puce/red/g'
perl -ne 'print if /Iowa/../Montana/'
perl -ne 'print $_ unless (/^$/ || /^\#/)'
%hash = ("abc" => 123, "def" => 456);$value = $hash{"key"};$ref = \%hash;print "$$ref{abc}"; # 输出哈希中的值sub function { ... }@list = function($i);$LoL[$i] = \$list; # 数组引用$LoL[$i] = scalar @list; # 数组值
open(IN, ";chomp(@raw);
$pattern = Pattern.compile("\\s+(.*),");$text =~ $pattern;Perl 在处理大文本时效率远高于 Java,例如正则匹配和字符串操作。
通过以上内容,初步掌握了 Perl 的基本语法和常用操作,包括数组、字符串、正则表达式和哈希的使用。随着更多实践,熟悉这些工具会显著提升你的编程效率。
转载地址:http://hwfx.baihongyu.com/