Perl中的对象和类之间有什么区别?

前端之家收集整理的这篇文章主要介绍了Perl中的对象和类之间有什么区别?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在解决一个对象和一个类之间的概念差异时遇到了一些麻烦.我真的不明白两者在任何编程语言中的区别,但目前我正在使用Perl和Moose,所以我更喜欢使用这些东西进行解释.

干杯

解决方法

有很多“一个类是一个蓝图,一个对象是从该蓝图构建的东西”,但是既然你已经要求使用Moose和Perl的一个具体例子,我想我会提供一个.

在下面的示例中,我们将有一个名为“Hacker”的类.该类(如蓝图)描述了黑客是什么(他们的属性)以及他们可以做什么(他们的方法):

package Hacker;       # Perl 5 spells 'class' as 'package'

use Moose;            # Also enables strict and warnings;

# Attributes in Moose are declared with 'has'.  So a hacker
# 'has' a given_name,a surname,a login name (which they can't change)
# and a list of languages they know.

has 'given_name'       => (is => 'rw',isa => 'Str');
has 'surname'          => (is => 'rw',isa => 'Str');
has 'login'            => (is => 'ro',isa => 'Str');
has 'languages'        => (is => 'rw',isa => 'ArrayRef[Str]');

# Methods are what a hacker can *do*,and are declared in basic Moose
# with subroutine declarations.

# As a simple method,hackers can return their full name when asked.

sub full_name {
    my ($self) = @_;   # $self is my specific hacker.

    # Attributes in Moose are automatically given 'accessor' methods,so
    # it's easy to query what they are for a specific ($self) hacker.

    return join(" ",$self->given_name,$self->surname);
}

# Hackers can also say hello.

sub say_hello {
    my ($self) = @_;

    print "Hello,my name is ",$self->full_name,"\n";

    return;
}

# Hackers can say which languages they like best.

sub praise_languages {
    my ($self) = @_;

    my $languages = $self->languages;

    print "I enjoy programming in: @$languages\n";

    return;
}

1;   # Perl likes files to end in a true value for historical reasons.

现在我们已经获得了Hacker类,我们可以开始制作Hacker对象了:

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

use Hacker;    # Assuming the above is in Hacker.pm

# $pjf is a Hacker object

my $pjf = Hacker->new(
    given_name => "Paul",surname    => "Fenwick",login      => "pjf",languages  => [ qw( Perl C JavaScript) ],);

# So is $jarich

my $jarich = Hacker->new(
    given_name => "Jacinta",surname    => "Richardson",login      => "jarich",languages  => [ qw( Perl C Haskell ) ],);

# $pjf can introduce themselves.

$pjf->say_hello;
$pjf->praise_languages;

print "\n----\n\n";

# So can $jarich

$jarich->say_hello;
$jarich->praise_languages;

这导致以下输出

Hello,my name is Paul Fenwick
I enjoy programming in: Perl C JavaScript

----

Hello,my name is Jacinta Richardson
I enjoy programming in: Perl C Haskell

如果我想要我可以拥有尽可能多的Hacker对象,但仍然只有一个Hacker类描述了所有这些对象的工作原理.

祝一切顺利,

保罗

原文链接:https://www.f2er.com/Perl/171746.html

猜你在找的Perl相关文章