Es gibt viele "eine Klasse ist ein Blueprint, ein Objekt ist etwas, das aus diesem Blueprint gebaut wurde", aber da Sie nach einem bestimmten Beispiel mit Moose und Perl gefragt haben, dachte ich, ich würde eins zur Verfügung stellen.
In diesem folgenden Beispiel haben wir eine Klasse namens "Hacker".Die Klasse (wie ein Bauplan) beschreibt, was Hacker sind (ihre Attribute) und was sie tun können (ihre Methoden):
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.
Jetzt, wo wir unsere Hacker Klasse haben, können wir beginnen Hacker machen Objekte:
#!/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;
Dieses in der folgenden Ausgabe führt:
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
Wenn ich will, ich ca Ich habe so viele Hacker-Objekte, wie ich möchte, aber es gibt immer noch nur eine Hacker-Klasse, die beschreibt, wie all diese funktionieren.
Alles Gute,
Paul
Wow, SUPER antwort .. kurze Zusammenfassung am Anfang, dann eine reale Welt Probe & Tutorial in Elch! DANKE! – lexu
Sehe jetzt dachte ich, das war übermäßig worry aber hey das ist nur ich. Gute Antwort. :) – cletus