#源文件如下:-------
#!/usr/bin/perl
use warnings;
use strict;
use vars qw/ %opts /;
&usage() if("@ARGV" =~ /--help/);
sub init(){
use Getopt::Std;
my $opt_str = 'esh';
getopts( "$opt_str",/%opts ) or &usage();
&usage() if $opts{h};
}
sub usage(){
print STDERR '
this program does../n
usage:$0 [-esh] file1 file2 file3 ... fileN
-h : this (help) messages
-e : desc count
-s : display /s+
example: $0 -e -s myfile
';
exit(0);
}
&init();
my @Contents= ();
my %Line_Count =();
my ($whidth,$wc_total) = (0,0);
my @sorted = ();
my @myFiles = &getFileFormAgument();
if(@myFiles > 0 ){
foreach my $f (@myFiles){
open (MYFILE,$f) or die "$f: Can't Open!$!/n";
@Contents = <MYFILE>;
close(MYFILE);
&wcEverLine();
if(exists $opts{"e"}){
&escLineByCount();
foreach my $hashref (@sorted) {
my ($k, $v) = each %$hashref;
printf " %${whidth}s %s/n",$v,$k;
}
}else{
while(my ($k,$v)= each(%Line_Count)){
printf " %${whidth}s %s/n",$v,$k;
}
}
printf " %${whidth}s total/n/n",$wc_total;
%Line_Count = ();
($whidth,$wc_total) = (0,0);
@sorted = {};
}
}else{
@Contents =<>;
&wcEverLine();
if(exists $opts{"e"}){
&escLineByCount();
foreach my $hashref (@sorted) {
my ($k, $v) = each %$hashref;
printf " %${whidth}s %s/n",$v,$k;
}
}else{
while(my ($k,$v)= each(%Line_Count)){
printf " %${whidth}s %s/n",$v,$k;
}
printf " %${whidth}s total/n/n",$wc_total;
}
}
sub wcEverLine{
foreach my $l (@Contents){
chomp $l;
if(exists $opts{"s"}){$l =~ s/^/s+//;$l =~ s//s+$//;}
$wc_total++;
$Line_Count{$l}++;
$whidth = length($Line_Count{$l}) if $whidth < length($Line_Count{$l});
}
$whidth =length($wc_total) if $whidth < length($wc_total);
}
sub escLineByCount{
@sorted = map { { ($_ => $Line_Count{$_}) } }
sort { $Line_Count{$a} <=> $Line_Count{$b} or $a cmp $b } keys %Line_Count;
}
sub getFileFormAgument {
my @augs = ();
foreach my $aug (@ARGV){
if($aug =~ /^-/){next;}else{
push(@augs,$aug);
}
}
return @augs;
}