前言
本文主要记录一下,perl中的切片操作。包括:
- 数组切片
- 哈希切片
19 切片
#=====================================
# 数组切片
#=====================================
while(<>){
chomp;
#方案1:
my @items = split /:/; #split按照:进行切分
my($card_num, $count) = ($items[1], $items[5]);
#方案2:
my (undef,$card_num, undef, undef, undef, $count) = split /:/;
#方案3:切片
my $card_num = (split /:/)[1];
my $count = (split /:/)[5];
#方案4:切片简化
my($card_num, $count) = (split /:/)[1,5];
print "$card_num, $count\n";
}
my @num = qw(0 1 2 3 4 5 6 7 8 9);
#切片提取
my ($first, $last) = @num[0,-1];
print "$first, $last\n"; #0, 9
#切片修改
@num[0,-1] = ("zero", "nine");
print "@num\n"; #zero 1 2 3 4 5 6 7 8 nine
#=====================================
# 哈希切片
#=====================================
#普通获取hash数据
my %scores = (0 => "zero", 1 => "one", 2 => "two", 3 => "three");
my @num = ($scores{0}, $scores{1}, $scores{2});
print "@num \n";
#hash切片获取hash数据
my @nums = @scores{qw/0 1 2/};
print "@nums \n";
#hash切片修改hash数据
my @values = qw/3 4 5/;
@scores{qw/0 1 2/} = @values;
while(my($k,$v) = each(%scores)){
print "$k => $v\n";
}
#3 => three
#2 => 5
#0 => 3
#1 => 4