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";
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";
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;
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.
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