Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does setting a class/module name before a variable definition do in Perl?

Tags:

perl

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?

like image 522
mfalkus Avatar asked Jul 19 '18 20:07

mfalkus


1 Answers

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 the fields pragma, and attributes are handled using the attributes pragma, or starting from Perl 5.8.0 also via the Attribute::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;
like image 83
Patrick Mevzek Avatar answered Nov 15 '22 09:11

Patrick Mevzek