文章目录
前言
本文主要记录一下,perl中的grep map操作。
18 grep map操作
#=====================================
# grep 筛选列表
#=====================================
my @odd_numbers;
foreach(1..1000){
push @odd_numbers, $_ if $_ % 2;
}
print "@odd_numbers\n";
# 上面的for循环和下边的grep等效
my @odd = grep {$_ % 2} 1..1000;
print "@odd\n";
# 上边的grep语句可以简化
my @odds = grep $_ % 2, 1..100;
print "@odds\n";
# 从文件中搜索line关键字,不区分大小写
my @matching_lines = grep /\bline\b/i, <>;
print "@matching_lines\n";
#=====================================
# 使用map转换列表,
#=====================================
#获取所有的txt文件
my @files = glob "*.*";
print "@files \n";
my @txt_files = map{/(.*\.txt)$/} @files;
print "@txt_files \n";
#上边的map可以简化为
my @txt_files = map /(.*\.txt)$/, @files;
print "@txt_files \n";
# 计算文件大小
my @sizes = map {-s} @txt_files;
print "@sizes \n";
# 对数据按照千分位格式化显示
sub big_money{
my $number = sprintf "%.2f", shift @_;
1 while $number =~ s/^(-?\d+)(\d\d\d)/$1,$2/;
$number =~ s/^(-?)/$1\$/;
$number; #returen
}
print (big_money 1234567.123); # $1,234,567.12
print "\n";
my @data = qw(123.67 34567.98 37383.987 33456.9876 2238474.98);
my @formatted_data;
# 利用循环进行操作
foreach(@data){
push @formatted_data, &big_money($_);
}
print "@formatted_data\n"; # $123.67 $34,567.98 $37,383.99 $33,456.99 $2,238,474.98
# 利用map进行操作
my @formatted = map {&big_money($_)} @data;
print "@formatted\n";
print "The money numbers are:\n", map {sprintf("%25s\n", $_)} @formatted;
#The money numbers are:
# $123.67
# $34,567.98
# $37,383.99
# $33,456.99
# $2,238,474.98
# 上边的map功能,一行搞定
print "The money numbers are:\n", map {sprintf("%25s\n", &big_money($_))} @data;
#利用map显示2的幂次方
print "Some powers of 2 are:\n", map "\t" . (2 ** $_) . "\n", 0..10;