您的位置:首页 > 编程语言

【设计分享】一个面向对象思想的perl编程实例

2014-08-21 22:02 585 查看
本身没有接触过面向对象的思想,最近这两天需要重构perl代码,下面是测试用的小段代码。

perl脚本的目标:根据提供的关键字,将设计文件中相应列元素出现次数进行统计,并输出。

包含文件:设计文件:design perl脚本: zengyihe.pl zengyihe.pm

zengyihe.pl文件:

1 #!/usr/bin/perl
2 use 5.010;
3 use warnings;
4 use strict;
5
6 push (@INC,'pwd');
7 use zengyihe;
8
9 open my $WRITE,">","./solution/answer";
10 my $name = "design";
11 my $key_words = "I_RISC_CORE";
12
13 my $tm = new zengyihe($name);
14 my %cell  = $tm->get_cell_hash($key_words,2);
15 my $output = $tm->get_output(\%cell);
16
17 print $WRITE $output;
18 close $WRITE;


zengyihe.pm文件:

1 #!/usr/bin/perl
2 use 5.010;
3 use warnings;
4 use strict;
5
6 package zengyihe;
7 require Exporter;
8 our     @ISA = qw(Exporter);
9 our     @EXPORT = qw();
10
11
12 sub new{
13     my $class = shift();
14     my $self  = {};
15     $self->{"name"} = shift();
16     bless $self , $class;
17     return $self;
18 }
19
20 sub get_name{
21     my ($self) = @_;
22     return $self->{"name"};
23 }
24
25 sub get_lines{
26     my ($self) = @_;
27     my $file = $self->get_name();
28     open my $fh,"<",$file;
29     chomp (my @lines = <$fh>);
30     close $fh;
31     return @lines;
32 }
33
34 sub get_cell_hash{
35     my ($self,$key_words,$row) = @_;
36     my @lines  = $self->get_lines();
37     my %cell;
38     foreach my $line (@lines){
39        if($line =~ /$key_words/){
40          my @tmp  = split /\s+/,$line;
41          my $cell = $tmp[$row-1];
42          $cell{$cell}++;
43        }
44     }
45     return %cell;
46 }
47
48 sub get_output{
49    my ($self,$cell) = @_;
50    my $output;
51    while (my($k,$v) = each %$cell){
52          $output .= $v."\t".$k."\n";
53   }
54   return $output;
55 }
56
57 1;



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: