Well, the Perl is easy, but I am rusty in the other languages, so I will update with them in a bit. Here is a plain Perl class:
#!/usr/bin/perl
package Person;
use strict;
use warnings;
use Carp;
sub new {
my $class = shift;
my $self = { @_ };
croak "bad arguments" unless defined $self->{firstname} and defined $self->{lastname};
return bless $self, $class; #this is what makes a reference into an object
}
sub name {
my $self = shift;
return "$self->{firstname} $self->{lastname}";
}
#and here is some code that uses it
package main;
my $person = Person->new(firstname => "Chas.", lastname => "Owens");
print $person->name, "\n";
Here is the same class written using the new Moose style objects:
#!/usr/bin/perl
package Person;
use Moose; #does use strict; use warnings; for you
has firstname => ( is => 'rw', isa => 'Str', required => 1 );
has lastname => ( is => 'rw', isa => 'Str', required => 1 );
sub name {
my $self = shift;
return $self->firstname . " " . $self->lastname;
}
#and here is some code that uses it
package main;
my $person = Person->new(firstname => "Chas.", lastname => "Owens");
print $person->name, "\n";
And MooseX::Declare removes the need for even more code and makes things look nice:
#!/usr/bin/perl
use MooseX::Declare;
class Person {
has firstname => ( is => 'rw', isa => 'Str', required => 1 );
has lastname => ( is => 'rw', isa => 'Str', required => 1 );
method name {
return $self->firstname . " " . $self->lastname;
}
}
#and here is some code that uses it
package main;
my $person = Person->new(firstname => "Chas.", lastname => "Owens");
print $person->name, "\n";
A quick note, These two class are the first two Moose classes I have ever written. And here is some very rusty C++ code (don't cut yourself on it or you will need a tetanus shot):
#include <stdio.h>
#include <string.h>
class Person {
char* firstname;
char* lastname;
public:
Person(char* first, char* last) {
firstname = first;
lastname = last;
}
char* name(void) {
int len = strlen(firstname) + strlen(lastname) + 1;
char* name = new char[len];
name[0] = '\0';
strcat(name, firstname);
strcat(name, " ");
strcat(name, lastname);
return name;
}
};
int main(void) {
Person* p = new Person("Chas.", "Owens");
char* name = p->name();
printf("%s\n", name);
delete name;
delete p;
return 0;
}