Perl 入門指南 - Encrypt.pm




Encrypt.pm 的程式原始碼如下

#!/usr/bin/perl
use strict;
use warnings;

package Encrypt;

use List::Util qw(shuffle); 

sub new {
    my $class = shift;
    my $self = {
        alph => shift,
        code => shift,
    };
    $self->{alph} = join("", ("a" .. "z"));
    $self->{code} = join("", shuffle(("a" .. "z")));
    bless $self, $class;
    return $self;
}

sub getCode {
    my $self = shift;
    return $self->{code};
}

sub setCode {
    my $self = shift;
    my $code = shift;
    $self->{code} = $code;
}

sub toEncode {
    my $self = shift;
    my $str_input = shift;
    
    my $str_result = "";
    my $i = 0;
    while ($i < length($str_input)) {
        my $s = substr($str_input, $i, 1);
        if ($s =~ /[a-z]/) {
            $str_result .= substr($self->{code}, index($self->{alph}, $s), 1);
        }
        else {
            $str_result .= $s;
        }
        
        $i++;
    }

    return $str_result;
}

sub toDecode {
    my $self = shift;
    my $str_input = shift;
    
    my $str_result = "";
    my $i = 0;
    while ($i < length($str_input)) {
        my $s = substr($str_input, $i, 1);
        if ($s =~ /[a-z]/) {
            $str_result .= substr($self->{alph}, index($self->{code}, $s), 1);
        }
        else {
            $str_result .= $s;
        }
        
        $i++;
    }

    return $str_result;
}

1;

# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:Encrypt.pm
# 功能:示範 Perl 程式
# 作者:張凱慶
# 時間:西元 2013 年 1 月   


您可以繼續參考
範例程式碼


相關目錄
回 Perl 入門指南
回 Perl 教材
回首頁


參考資料
http://www.perl.org/
http://learn.perl.org/
http://perldoc.perl.org/index.html
http://www.tutorialspoint.com/perl/index.htm
http://perl-begin.org/
http://www.bin-co.com/perl/perl_tk_tutorial/

沒有留言: