perl数据操作

一次给多个变量赋值
($a, $b, $c) = ("aaa", "bbb", "ccc");
print "$a  $b  $c\n";
或者
@ls = ("aaa", "bbb", "ccc");
($a, $b, $c) = @ls;
print "$a  $b  $c\n";

散列
%longday =
(
        "Sun" => "Sunday",
        "Mon" => "Monday",
        "Tue" => "Tuesday",
        "Wed" => "Wednesday",
        "Thu" => "Thursday",
        "Fri" => "Friday",
        "Sat" => "Saturday",
        "All" => ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
);

print $longday{"Sun"}."\n";
print $longday{"All"}[1]."\n";

遍历散列(如环境变量)
foreach $key (keys %ENV) {
        print "$key = $ENV{$key}\n";
}
while(($key, $value) = each(%ENV)) {
        print $key." = ".$ENV{$key}." = ". $value ."\n";
}




数组
给数组赋值
@ls = "a" .. "z";
for(@ls){print $_, "\n";}

利用qw定义数组,可以省去引号和都好
@ls = qw(aaa bbb ccc ddd);
for (@ls){print $_, "\n";}
qw允许用其它符号代替括号,甚至是注释符号
@l = qw#aaa bbb ccc ddd#;


数组扩容
@a = ("a", "b");
@a = (@a, "x");
print $a[2]; 输出x

push和pop
push从下标加1开始追加,
pop从下标最大开始减
@ls = qw(a b c);
for(@ls){print $_, " ";}
print "\n";
push @ls, "l";
push @ls, "m";
push @ls, "n";
for(@ls){print $_, " ";}
print "\n";
@xyz = qw(x y z);
push @ls, @xyz;

for(@ls){print $_, " ";}
print "\n";
print " POP:", pop @ls;
print " POP:", pop @ls;
print " POP:", pop @ls;
print "\n";
for(@ls){print $_, " ";}
print "\n";

输出:
a b c
a b c l m n
a b c l m n x y z
POP:z POP:y POP:x
a b c l m n 

排序和翻转
@ls = sort qw(b a c);  得到 a b c
@ls = reverse qw(a b c); 得到 c b a


循环的时候
@a = ("asd", "bsd");
@a = (@a, "csd");
foreach (@a)
{
     next if /b/;    next相当于continue,这里指跳过“bsd”
     print;          循环体内,$_代表当前的循环内容,命令中如果没有操作数,则默认是对$_操作
     switch 
     case /^a/ {...}
     case /^b/ {...}
     case /^c/ {...}
}

几种switch(last相当于break)
foreach (@a)
{
     switch: 
     {
          if(/^a/) {...; last switch} 
          if(/^b/) {...; last switch}
          if(/^c/) {...; last switch}
     }
     或者
     switch: 
     {
          /^a/ && do {...; last switch};
          /^b/ && do {...; last switch};
          /^c/ && do {...; last switch};
     }
}

用户输入
$line = ;
print $line;
通过STDIN的方式,获取的输入内容是带有换行符的,因此,在实际使用中,需要用chomp,获取不带换行符的用户输入。
$line = ;
chomp $line;
print $line;
chomp ($line = );
print $line;

判断变量是否被定义
if (defined($a)) {print "defined", "\n";} else {print "undefined", "\n";}
$a=123;
if (defined($a)) {print "defined", "\n";} else {print "undefined", "\n";}
输出
[root@server2 pl]# ./a.pl
undefined
defined




























来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/26239116/viewspace-2125607/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/26239116/viewspace-2125607/

你可能感兴趣的:(perl数据操作)