Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl accessing package constant from different package

Tags:

perl

I'm new to Perl and I'm learning OOP in Perl right now.

Is there a way without any additional libraries (it is forbidden to use any additional lib) to access variable from one package in another one?

package Class;

my $CONSTANT = 'foo'; # this doesn't work, neither our $CONSTANT ..

# ...
# class methodes
# ...

package main;

print Class::$CONSTANT ."\n";
like image 621
Hologos Avatar asked Feb 16 '23 11:02

Hologos


1 Answers

Your constant declaration is wrong

Constants do not have a $ before their name because they are not variables -- a variable (as implied by the name) contains a value which can vary.

Try this (it uses the constant module but that's included in the default installation:

use constant CONSTANT => "Foo";

Accessing class constants

You can then access them as:

Class::CONSTANT # I suggest NOT using this as 'Class::Constant' is a module name, rename your class to something useful

Or, if you have $obj as an instance of Class:

$obj->CONSTANT;

Sample code showing both access methods

use warnings;
use strict;

package MyClass;
use constant SOME_CONSTANT => 'Foo';
sub new
{
   my $type = shift;                   # The package/type name
   my $self = {};                      # Empty hash
   return bless $self, $type;
}

package main;
print MyClass::SOME_CONSTANT . "\n";   # Prints 'Foo\n'

my $obj = MyClass->new();
print $obj->SOME_CONSTANT;             # Prints 'Foo'

And a demo.

like image 197
Glitch Desire Avatar answered Mar 04 '23 10:03

Glitch Desire