New Tricks
As of v5.6, you can also declare a method to indicate that it returns an lvalue. This is done with the lvalue subroutine attribute (not to be confused with object attributes). This experimental feature allows you to treat the method as something that would appear on the lefthand side of an equals sign:
package Critter;
sub new {
my $class = shift;
my $self = { pups => 0, @_ }; # Override default.
bless $self, $class;
}
sub pups : lvalue { # We'll assign to pups() later.
my $self = shift;
$self–>{pups};
}
package main;
$varmint = Critter–>new(pups => 4);
$varmint–>pups *= 2; # Assign to $varmint–>pups!
$varmint–>pups =~ s/(.)/$1$1/; # Modify $varmint–>pups in place!
print $varmint–>pups; # Now we have 88 pups.This lets you pretend $varmint–>pups is a variable while still
obeying encapsulation. See the section The lvalue Attribute
in Chapter 7.
If you’re running a threaded version of Perl and want to ensure
that only one thread can call a particular method on an object, you can
use the locked and method attributes to do that:
sub pups : locked method {
...
}When any thread invokes the pups method on an object, Perl locks the
object before execution, preventing other threads from doing the same.
See the section The method Attribute in Chapter 7.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access