perl 面向对象编程

今天看到一个perl面向对象编程的例子,充分体现了如何对数据进行封装;

自己模仿写一个读取配置文件的例子, 配置文件的内容如下

samtools_binary = /usr/bin/samtools

用=分隔,保存了每个软件可执行文件的绝对路径;

下面用perl 模块进行配置文件的读取, 模块名为config.pm

package config;

use strict;
use warnings FATAL => 'all';

sub new 
{
    my $self = {};
    
    bless($self);

    return $self;
}

sub read 
{
    my $self = shift;
    my $config_filename = shift;

    my %config_values;

    open CFG, $config_filename or die "Error: Unable to open $config_filename\n";
    while (<CFG>) 
    {
        chomp;
        next if /^#/;
        next if /^\s*$/;

        my ($key, $value) = split /=/, $_, 2;

        next if not defined $key;
        next if not defined $value;

        $key   =~ s/^\s*(\S+)\s*$/$1/;
        $value =~ s/^\s*(\S+)\s*$/$1/;

        $config_values{$key} = $value;
    }
    close CFG;
    $self->{'config_values'}   = \%config_values;
    $self->{'config_filename'} = $config_filename;
}

sub get_value {
    my $self = shift;
    my $key  = shift;

    my $config_values   = $self->{'config_values'};
    my $config_filename = $self->{'config_filename'};

    defined $config_values->{$key} or die "Error:no values for $key at $config_filename\n";
    return $config_values->{$key};
}

1;

然后在脚本中调用这个模块

#!/usr/bin/perl

use lib qq{./};
use config;

my $config = config->new;
my $config_filename = qq{config.txt};
$config->read($config_filename);
print $config->get_value(qq{samtools_binary});

在config.pm中,可以将config看作一个类,而new函数返回对该类的一个对象的引用;

在read函数中,通过在对象和我们真正想要读取的值之间添加一层哈希,对数据进行封装;

在看不到源代码的情况下,只能通过指定的get_value 方法读取配置文件中参数的值;

如果写成下面这样,就实现不了封装的效果

package config;

use strict;
use warnings FATAL => 'all';

sub new 
{
    my $self = {};
    
    bless($self);

    return $self;
}

sub read 
{
    my $self = shift;
    my $config_filename = shift;

    my %config_values;

    open CFG, $config_filename or die "Error: Unable to open $config_filename\n";
    while (<CFG>) 
    {
        chomp;
        next if /^#/;
        next if /^\s*$/;

        my ($key, $value) = split /=/, $_, 2;

        next if not defined $key;
        next if not defined $value;

        $key   =~ s/^\s*(\S+)\s*$/$1/;
        $value =~ s/^\s*(\S+)\s*$/$1/;

        $self->{$key} = $value;
    }
    close CFG;
    $self->{'config_filename'} = $config_filename;
}

sub get_value {
    my $self = shift;
    my $key  = shift;


    defined $self->{$key} or die "Error:no values for $key\n";
    return $self->{$key};
}

1;

 

  

你可能感兴趣的:(perl 面向对象编程)