Perl accessing package constant from different package
perl
Solution
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.
Problem
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"; ```