Perl 基础知识分享(1)
@(运维Devops知识库)[perl基础知识]
变量
标量变量
标量可以包含字符串、数字、对象、引用.
my $name = "John"; # this is a string
my $age = 28; # this is a number (integer)
my $float = 28.5; # also a number, but a float
my $car = Car->new(); # this is an object from the class Car
数组变量
数组列表。像一个购物清单。他们包含了很多的标量.
my @names = ("John", "Fred", "Charley");
my @to_buy = qw(Cheese Butter Salt Lemons Oranges Apples);
访问数组元素必须使用索引。索引是从零开始的:
say "First name: " . $names[0];
say "Last name: " . $name[2];
say "Also last name: " . $name[-1];
分割字符串成数组:
my $string = "John,Fred,Carl,Lewis";
my @names = split(/,/, $string);
把数组连接成一个字符串:
my @names = ("John", "Fred", "Carl", "Lewis");
my $string = join(",", @names); # -> John,Fred,Carl,Lewis
如果你想遍历一个数组,这样做:
for my $name (@names) {
say "Current name: $name";
}
哈希变量
hashs 比较像数组,但是它有着命名的索引,一般叫做键。
my %person = (
name => "John",
age => 28,
city => "New York"
);
访问一个hash 必须用key:
say "Name: " . $person{"name"};
say "Age: " . $person{"age"};
say "City: " . $person{"city"};
如果你遍历hash 可以这样做. 但是没有排序.
for my $key ( keys %person ) {
say "key: $key -> value: " . $person{$key};
}
条件语句
if ( $name eq "John" ) {
say "Hello, my name is John!";
} else {
say "Well, my name is not John...";
}
if ( $name ne "John" ) {
say "Yes, my name is NOT John...";
} else {
say "Hello, my name is John!";
}
if ( $age < 30 ) {
say "I'm younger than 30.";
} elsif ( $age >= 30 && $age <= 50 ) {
say "Well, I'm between 30 and 50.";
} else {
say "I'm older than 50.";
}
循环
for my $num (1..5) {
say "> $num";
}
# looping over an array
for my $item (@array) {
say "> $item";
}
正则表达式
my $name = "John";
if ( $name =~ m/john/ ) { # will not match, because the "J" in $name is uppercase
}
if ( $name =~ m/john/i ) { # _will_ match, because we use the "i" modifier for case-insensitive matching
}
$name =~ s/john/Fred/i; # this will replace the first match of "john" (regardless of its case) with "Fred"
$name =~ s/john/Fred/ig; # this will replace all matches of "john" (regardless of its case) with "Fred"
函数
sub my_function { # define the function called "my_function"
}
sub my_function { # define the function called "my_function"
my $param1 = $_[0]; # get the 1st parameter and save it in $param1
my $param2 = $_[1]; # get the 2nd parameter and save it in $param2
my $param3 = $_[2]; # get the 3rd parameter and save it in $param3
}
sub my_function {
my ($param1, $param2, $param3) = @_; # the same as above
}
my_function(); # call the function "my_function"
my_function; # also calls "my_function"
&my_function; # also calls "my_function"
my_function("john", 28); # call "my_function" with 2 parameters
my_function "john", 28; # also calls "my_function" with 2 parameters: the brackets are not needed
辅助函数
打印一个列表上下文,数组,hash
use Data::Dumper;
say Dumper($scalar);
say Dumper(@array);
say Dumper(%hash);
网友评论