打卡9:perl grep/map
发布时间:2020-12-15 23:56:56 所属栏目:大数据 来源:网络整理
导读:1 while () { @d=grep {/$_/} @b;-----------------注意此处的$_已经是grep中的$_了,不是while的。 $l=@d; if ($l==0) { push (@b,$_); }} 改为 while(my $line=){ @d = grep{ $line ne $_} @b; push @d,$line;} 2 my @b=();my @d=();#my %a;while () { @d=
1
while (<>) { @d=grep {/$_/} @b;-----------------注意此处的$_已经是grep中的$_了,不是while的。 $l=@d; if ($l==0) { push (@b,$_); } }改为 while(my $line=<>){ @d = grep{ $line ne $_} @b; push @d,$line; }2 my @b=(); my @d=(); #my %a; while (<>) { @d=grep {/$_/} @b; $l=@d; print "1:l=$l:d=@d:b=@b;cu=$_n"; if ($l==0) { push (@b,$_); } } 3 map =================================== find 递归 #!/opt/exp/bin/perl -w use strict; use warnings; use File::Find; my ($size,$dircnt,$filecnt) = (0,0); sub process { my $file = $File::Find::name; if (-d $file) { $dircnt++; } else { $filecnt++; $size += -s $file; } print "line17:$filen"; } find(&;process,'.'); print "$filecnt files,$dircnt directory. $size bytes. "; 自己的理解:
?参数2是init的path,find会自己foreach?文件,然后call子函数;然后发现目录,在自动递归。
同比shell的find是 find * -name "*" -print. 也在自动递归
find实现,不用find函数,递归
#!/opt/exp/bin/perl -w use strict; use warnings; sub lsr($) { sub lsr; my $cwd = shift; local *DH; if (!opendir(DH,$cwd)) { warn "Cannot opendir $cwd: $! $^E"; return undef; } foreach (readdir(DH)) { if ($_ eq '.' || $_ eq '..') { next; } my $file = $cwd.'/'.$_; if (!-l $file && -d _) { $file .= '/'; lsr($file); } # process($file,$cwd); process($file); } closedir(DH); } my ($size,0); sub process($$) { my $file = shift; print $file,"n"; if (substr($file,length($file)-1,1) eq '/') { $dircnt++; } else { $filecnt++; $size += -s $file; } } lsr('.'); print "$filecnt files,$dircnt directory. $size bytes.n"; find实现,不用find函数,非递归 #!/opt/exp/bin/perl -w use strict; use warnings; sub lsr_s($) { my $cwd = shift; my @dirs = ($cwd.'/'); my ($dir,$file); while ($dir = pop(@dirs)) { local *DH; if (!opendir(DH,$dir)) { warn "Cannot opendir $dir: $! $^E"; next; } foreach (readdir(DH)) { if ($_ eq '.' || $_ eq '..') { next; } $file = $dir.$_; if (!-l $file && -d _) { $file .= '/'; push(@dirs,$file); } # process($file,$dir); process($file); } closedir(DH); } } my ($size,0); sub process($$) { my $file = shift; print $file,1) eq '/') { $dircnt++; } else { $filecnt++; $size += -s $file; } } lsr_s('.'); print "$filecnt files,$dircnt directory. $size bytes.n"; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |