PERL学习

吐槽、建议、解惑入口网址
perl 是脚本语言,在工作部署、编译等一些关于linux服务器上的事情都会跟perl打交道。写下自己学习路程,给自己日后总结。

文档查询

perldoc -f xxxx

perl数据类型

字符串

定义字符串变量: my $name (my: 定义变量 $: 表示字符串 name: 变量名)
注意点

  • 内插型字符串

    其他变量的数据可以在插入字符串中展示

1
2
my $name = "Inigo MOntoya";
print "My name is $name";
  • 非内插型字符串

    无论什么字符都直接展示

1
print 'You may have won $1,000,000';
  • 转义字符

    有些特殊字符需要转义才能正输出

1
2
3
4
5
my $email = "andy@foo.com";
print $email;
# Prints "andy.com"
解决方案:
my $email = "andy\@foo.com";

字符串操作函数

  • length() 获取字符串长度
  • subStr() 能够截取字符串

数组

  • 创建

  • 访问 $stooges[1]

  • 数组长度 @stooges scalar @stooges

  • 数组特性

    • 数组没有边界
    • 数组合并会平展元素
  • 数组操作方法

    • shift 从数组开头移除元素
    • unshift 将元素添加到数组开头
    • push 将元素添加到数组的结尾
    • pop 从数组的结尾移除元素
  • 数组高级用法

    • 提取数组的部分元素

      1
      2
      my @a = 'a'..'z';
      my @vowels = @a[0, 4, 8, 14, 20];
    • 分配数组块 使用splice

    1
    2
    3
    4
    5
    6
    7
    8
    使用场景 数组拼接
    my @a = qw(Steve Stu Stan);
    $a[1] = ['Stewart', 'Zane'];
    # @a = ('Steve', ARRAY(0x841214c), 'Stan')

    my @a = qw(Steve Stu Stan);
    splice @a 1, 1, 'Stewart', 'Zane';
    #@a = ('Steve', 'Stewart', 'Zane', 'Stan')
    • 利用map处理数组 (map 本质上是返回列表的foreach 循环)map
    1
    2
    3
    my @ARRAY = (1, 2, 3, 4, 5);
    my %hash = map {$_ => $_ * 9} @ARRAY;
    # %hash = (1 => 9, 2 => 18, 3 => 27, 4 => 36, 5 => 45)
    • grep从数组中选择项目 (grep 本质上返回列表foreach循环)
      1
      2
      3
      my @ARRAY = (1, 2, 3, 4, 5);
      my @NEWARRAY = grep {$_ * 9} @ARRAY
      {} 包含表达式的意思

哈希

哈希就是键值对

  • 创建
1
2
3
4
5
6
7
8
9
10
1.方法一
my %stooges = (
'Moe', 'Howard',
'Larry', 'Fine',
);
2. 方法二
my %stooges = (
Moe => 'Howard',
Larry => 'Fine',
)
  • 哈希转数组
1
2
my @hash_array = %stooges;
# Contains ('Moe', 'Howard', 'Larry', 'Fine');
  • 使用{}操作哈希
    输出哈希值 更改哈希值 删除哈希条目

    1
    2
    3
    4
    5
    6
    print $stooges{'Moe'};
    #Prints "Howard";
    $stooges{'Moe'} = 'NiHao';
    delete $stooges{'Moe'};
    unlink $stooges{'Moe'};
    delete 不会删除文件 unlink 为删除文件
  • 哈希的键/值数组

1
2
my @key = keys %stooges;
my @value = values %stooges;
  • 哈希特点

    • 哈希是无序的
    • 无法排序
  • 哈希define exist的差异

不曾拥有,所以努力。(坚持原创技术分享,您的支持将鼓励我继续创作!)