Whilst working with the Net::SIP
module I noticed in some of the functions there is code that defines the class of an argument. For example:
sub can_deliver_to {
my Net::SIP::Leg $self = shift;
[...]
return 1;
}
What purpose does specifying Net::SIP::Leg
have on defining $self
? Is it just syntactic sugar to aid the developer in knowing what type of variable $self
should be?
It provokes a compile time error, in cases the structure/object is accessed in some invalid way.
See https://perldoc.perl.org/functions/my.html
my VARLIST my TYPE VARLIST my VARLIST : ATTRS my TYPE VARLIST : ATTRS
A
my
declares the listed variables to be local (lexically) to the enclosing block, file, or eval. If more than one variable is listed, the list must be placed in parentheses.The exact semantics and interface of TYPE and ATTRS are still evolving. TYPE may be a bareword, a constant declared with
use constant
, or__PACKAGE__
. It is currently bound to the use of thefields
pragma, and attributes are handled using theattributes
pragma, or starting from Perl 5.8.0 also via theAttribute::Handlers
module.
And if you jump at the documentation on fields
at https://perldoc.perl.org/fields.html you get this example:
{
package Foo;
use fields qw(foo bar _Foo_private);
sub new {
my Foo $self = shift;
unless (ref $self) {
$self = fields::new($self);
$self->{_Foo_private} = "this is Foo's secret";
}
$self->{foo} = 10;
$self->{bar} = 20;
return $self;
}
}
my $var = Foo->new;
$var->{foo} = 42;
# this will generate a run-time error
$var->{zap} = 42;
# this will generate a compile-time error
my Foo $foo = Foo->new;
$foo->{zap} = 24;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With