4.3.2. Defining Methods
You define a method for this class by defining a function in that namespace that accepts the object's instance as its first argument.
Here are two example methods in the class Foo
, that retrieve and set its name:
sub get_name { # This step is necessary so it will be treated as a method my $self = shift; return $self->{'name'}; } sub assign_name { my $self = shift; # Notice that we can pass regular arguments from now on. my $new_name = shift || "Fooish"; $self->{'name'} = $new_name; return 0; }
And here's a script that makes use of these functions. Can you guess what its output would be?
#!/usr/bin/env perl use strict; use warnings; use Foo; my $foo = Foo->new("MyFoo", 500); print $foo->get_name(), "\n"; $foo->assign_name("Shlomi Fish"); print $foo->get_name(), "\n";